Middle
What is a decorator in the context of programming?
sobes.tech AI
Answer from AI
Decorator is a design pattern that allows dynamically adding new behavior to existing objects by wrapping them in special "wrapper objects" without changing their structure.
Key principles:
- Dynamic addition of behavior: Functionality is added at runtime, not statically.
- Transparency for the client: Client code interacts with the decorator as if it were the original object.
- Flexibility: Allows combining different decorators to achieve the desired behavior.
Example in Python:
def my_decorator(func):
def wrapper():
print("Before calling the function")
func()
print("After calling the function")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
# Calling the function with the decorator applied
say_hello()
In this example, @my_decorator is syntactic sugar equivalent to say_hello = my_decorator(say_hello).
Example in JavaScript:
function logCall(target, key, descriptor) {
const originalMethod = descriptor.value;
descriptor.value = function(...args) {
console.log(`Calling method ${key} with arguments: ${args}`);
const result = originalMethod.apply(this, args);
console.log(`Method ${key} returned: ${result}`);
return result;
};
return descriptor;
}
class Example {
@logCall
add(a, b) {
return a + b;
}
}
const instance = new Example();
instance.add(2, 3);
Here, @logCall is used to add logging to the add method of the Example class.
Application in QA Automation:
- Logging: Adding logs to test steps or interactions with elements.
- Exception handling: Wrapping function calls to handle specific exceptions.
- State management: Changing object state before or after calling its methods (e.g., switching contexts).
- Authentication/authorization: Checking access rights before performing a specific action.