I have started using the following in my automation code in instances where I'm not interested in keeping the object 'alive'and just using it as a means as a type of precondition. For example:

Instead of the following:

Login login = new Login()

I do the following instead (as an example!):

new Login().SetUserName(username).SetPassword(myPassword).Submit()

In the above example, what is this technique called, and is it wise to use it in the way that I'm doing?



It's called fluent interface and it's neither generally bad nor good, it depends on the implementation.

Personally I don't think your example adds anything in readability over your own example or even just:

 var login = new Login();

The main point of "fluent" is readability and type-safety in combining options.

One question would be, does this:

new Login().SetUserName(username).SetPassword(myPassword).Submit()

add anything over the static method

Login.Submit(username, password);

If it does (for example because it has different overloads for the Login constructor to inject another HTTP client or something like that) then great. If not, I would wonder why you make it so complicated.

|improve this answer|||||
  • I've updated my question. Hopefully I've made it clearer. – yorkshireflatcap Oct 8 '18 at 9:19
  • As per the article you link to, it's called a fluent interface, not a fluid one ;) – David Arno Oct 8 '18 at 10:28
  • @DavidArno lol, you're right, I mixed that up, same word in my native language :) – nvoigt Oct 8 '18 at 11:05

From the compiler's point of view, your two versions are no different. The login variable will just be optimised away in the first example as it's not needed. So really, it just becomes a matter of personal style as to which you use.

A third option is to replace the new Login() with a static method that returns the login object for your fluent interface, eg:


but again, this is very much a style thing. There's no correct way to do this and there's no specific terms to distinguish your two approaches.

|improve this answer|||||
  • Thanks guys for your input and suggestions - very helpful. Unfortunately, I can't upvote as my reputation score does not allow me. – yorkshireflatcap Oct 9 '18 at 9:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.