Your opinions on these two code snippets? RRS feed

  • General discussion

  • I try to continuously refine my code for computing efficiency and human readability. It's a balance, and there's a sweet spot: some code is very efficient but very unreadable, and some very readable code is completely inefficient.

    I have here an object called "browser" that holds a web browser created through Selenium. We give it a URL and navigate to it.

    browser.Url = My.Settings.Website

    Now we need to log in. We can do it these two ways.

    Snippet #1

    Dim element As IWebElement
    element = browser.FindElementById("username")
    element = browser.FindElementById("password")
    element = browser.FindElementById("loginSubmit")

    Snippet #2

    DirectCast(browser.FindElementById("username"), IWebElement).SendKeys(My.Settings.Login)
    DirectCast(browser.FindElementById("password"), IWebElement).SendKeys(My.Settings.Password)
    DirectCast(browser.FindElementById("loginSubmit"), IWebElement).Submit()

    It seems to me (BICBW) that Snippet #2 is really just as readable as Snippet #1 yet much more succinct, plus we even save a few bytes by not having to create a variable. What do you think?

    Saturday, March 30, 2019 8:33 PM

All replies

  • Hi

    My way of thinking is that the readability of the code depends entirely on the comments included. Anyone who writes the code presumable understands the results of a piece of code, but is likely to forget the 'why' he/she wrote that piece of code - what/why aspect, to me. is more important and is accomplished by copious comments.

    I must admit to being somewhat lax in heeding my own advice though. But, where I did take the time to do it, and subsequently needing to edit/amend/fix something, then it becomes clear.

    So, to answer your question, in my opinion, each of the snippets is as good as the other, and both would be immensley improved by comments. (for future reference)

    Regards Les, Livingston, Scotland

    Saturday, March 30, 2019 9:08 PM
  • I would go with snippet 1 and add assertion on each usage of FindElementById. Thinking past readability, the first example would be easy to trace code via breakpoints while not so easy with code example 2.

    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    profile for Karen Payne on Stack Exchange

    Saturday, March 30, 2019 10:15 PM