0

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()
login.SetUserName(username).SetPassword(password).Submit()

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?

Thanks.

  • Related: [Are there any actual drawbacks to self-referential method chaining?](https://softwareengineering.stackexchange.com/q/80244/118878) – Greg Burghardt Oct 08 '18 at 11:23
  • 1
    Possible duplicate of [Are there any actual drawbacks to self-referential method chaining?](https://softwareengineering.stackexchange.com/questions/80244/are-there-any-actual-drawbacks-to-self-referential-method-chaining) – Bent Oct 08 '18 at 17:55

2 Answers2

1

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();
     login.SetUserName(username);
     login.SetPassword(myPassword);
     login.Submit();

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.

nvoigt
  • 7,271
  • 3
  • 22
  • 26
0

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:

Login.Create().SetUserName(username).SetPassword(myPassword).Submit();

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.

David Arno
  • 38,972
  • 9
  • 88
  • 121