Sobes.tech
Junior

After which functions can you put a semicolon and continue calling the next method?

sobes.tech AI

Answer from AI

After functions that return an object (including the current object) of the same class or a class with a similar interface that allows chaining. This is possible thanks to the Method Chaining design pattern.

Examples of such cases:

  • Getters that return an object: object.getProperty().anotherMethod()
  • Setters that return this: object.setProperty(value).anotherProperty(value2)
  • Methods that return a new object of the same type: object.filter(...).sort(...)
  • Creating and configuring objects: new Builder().step1().step2().build()
# Example of Method Chaining in Python
class Car:
    def __init__(self):
        self.color = None
        self.engine = None

    def set_color(self, color):
        self.color = color
        return self # Return self to continue chaining

    def set_engine(self, engine):
        self.engine = engine
        return self

    def drive(self):
        print(f"Driving a {self.color} car with a {self.engine} engine.")

# Using Method Chaining
my_car = Car().set_color("red").set_engine("V8")
my_car.drive()