wasAsked.

explain abstraction in hooks

PwC · Full Stack Developer · technical

Published

Year not specified · C#

Community answers

Posted by wasAsked editorial collection

"Hooks" can mean two things in interviews, and both are good examples of abstraction — hiding implementation details behind a simple interface. Clarify which one the interviewer means, then answer. 1. Hooks as extension points in object-oriented design (C#) A base class defines the overall algorithm and exposes "hook" methods that subclasses can optionally override. Callers use the simple public method; the details are abstracted away. This is the Template Method pattern. public abstract class ReportGenerator { // Public abstraction: callers only know "Generate" public string Generate(ReportData data) { OnBeforeGenerate(data); // hook (optional) var body = BuildBody(data); // abstract step (required) var result = Header() + body + Footer(); OnAfterGenerate(result); // hook (optional) return result; } protected abstract string BuildBody(ReportData data); protected virtual string Header() => "Company Report\n"; protected virtual string Footer() => "\nGenerated by system"; protected virtual void OnBeforeGenerate(ReportData data) { } // empty default hook protected virtual void OnAfterGenerate(string output) { } } public sealed class SalesReport : ReportGenerator { protected override string BuildBody(ReportData d) => $"Sales: {d.Total:C}"; protected override void OnAfterGenerate(string output) => Audit.Log("Sales report created"); } Abstraction here: the caller does not know how reports are built; subclasses fill in steps without changing the overall flow. ASP.NET Core uses the same idea — for example, overriding OnModelCreating or SaveChangesAsync in DbContext, or ExecuteAsync in BackgroundService. 2. Hooks in React (custom hooks) Custom hooks abstract stateful logic so components stay simple: function useOrders(customerId: string) { const [orders, setOrders] = useState<Order[]>([]); const [loading, setLoading] = useState(true); useEffect(() => { const ctrl = new AbortController(); fetch(`/api/customers/${customerId}/orders`, { signal: ctrl.signal }) .then(r => r.json()).then(setOrders).finally(() => setLoading(false)); return () => ctrl.abort(); }, [customerId]); return { orders, loading }; } // The component only knows the abstraction: const { orders, loading } = useOrders(id); The component does not know about fetch, cancellation or state handling; the hook hides those details and can be reused and tested independently. Either way, abstraction means exposing what something does while hiding how it does it, which reduces coupling and makes the implementation changeable.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics