{"id":"6b093dc091bd8fbaf2a0c8bc","slug":"catalog-specification","title":"Specyfikacje w katalogu sklepu","summary":"Reguły promocji jako małe obiekty, które się składa operatorami and, or i not – wzorzec Specyfikacja z DDD, własne reguły i wyszukiwanie w katalogu.","servedLang":"pl","availableLangs":["pl","en"],"kind":"code","category":"pattern","status":"published","difficulty":"medium","topics":["specification"],"techs":["typescript","javascript","python","dotnet","java","go"],"tags":["specification","ddd","composite","business-rules","e-commerce"],"languages":[{"lang":"typescript","runner":"browser","starter":"interface Product {\n  name: string;\n  category: string;\n  price: number;\n  stock: number;\n}\n\n/** A business rule that can be checked against a candidate and combined with other rules. */\ninterface Specification<T> {\n  isSatisfiedBy(candidate: T): boolean;\n  and(other: Specification<T>): Specification<T>;\n  or(other: Specification<T>): Specification<T>;\n  not(): Specification<T>;\n}\n\n/** Base class: concrete rules implement only isSatisfiedBy(), composition is inherited. */\nabstract class CompositeSpecification<T> implements Specification<T> {\n  abstract isSatisfiedBy(candidate: T): boolean;\n\n  and(other: Specification<T>): Specification<T> {\n    // TODO: a new specification satisfied when this AND other are satisfied\n    throw new Error('Not implemented');\n  }\n\n  or(other: Specification<T>): Specification<T> {\n    // TODO: a new specification satisfied when this OR other is satisfied\n    throw new Error('Not implemented');\n  }\n\n  not(): Specification<T> {\n    // TODO: a new specification satisfied when this one is NOT satisfied\n    throw new Error('Not implemented');\n  }\n}\n\n// TODO: AndSpecification, OrSpecification, NotSpecification (they extend CompositeSpecification too)\n\nclass InStock extends CompositeSpecification<Product> {\n  isSatisfiedBy(product: Product): boolean {\n    // TODO: stock > 0\n    throw new Error('Not implemented');\n  }\n}\n\nclass PriceAtMost extends CompositeSpecification<Product> {\n  constructor(private readonly max: number) {\n    super();\n  }\n\n  isSatisfiedBy(product: Product): boolean {\n    // TODO: price <= max\n    throw new Error('Not implemented');\n  }\n}\n\nclass InCategory extends CompositeSpecification<Product> {\n  constructor(private readonly category: string) {\n    super();\n  }\n\n  isSatisfiedBy(product: Product): boolean {\n    // TODO: exact category match\n    throw new Error('Not implemented');\n  }\n}\n\nclass Catalog {\n  constructor(private readonly products: Product[]) {}\n\n  /** Products satisfying the specification, in catalog order. */\n  find(spec: Specification<Product>): Product[] {\n    throw new Error('Not implemented');\n  }\n\n  count(spec: Specification<Product>): number {\n    throw new Error('Not implemented');\n  }\n}\n","testCount":8,"tests":"const SAMPLE_PRODUCTS = [\n  { name: 'Clean Code', category: 'books', price: 39, stock: 5 },\n  { name: 'Refactoring', category: 'books', price: 55, stock: 0 },\n  { name: 'Catan', category: 'games', price: 45, stock: 2 },\n  { name: 'Chess Set', category: 'games', price: 25, stock: 0 },\n  { name: 'USB Cable', category: 'electronics', price: 9, stock: 120 },\n  { name: 'Headphones', category: 'electronics', price: 199, stock: 7 },\n];\nconst namesOf = (products) => products.map((p) => p.name);\n\ntest('basic rules check a single product', () => {\n  const [cleanCode, refactoring] = SAMPLE_PRODUCTS;\n  expect(new InStock().isSatisfiedBy(cleanCode)).toBe(true);\n  expect(new InStock().isSatisfiedBy(refactoring)).toBe(false);\n  expect(new PriceAtMost(39).isSatisfiedBy(cleanCode)).toBe(true);\n  expect(new PriceAtMost(39).isSatisfiedBy(refactoring)).toBe(false);\n  expect(new InCategory('books').isSatisfiedBy(cleanCode)).toBe(true);\n  expect(new InCategory('games').isSatisfiedBy(cleanCode)).toBe(false);\n});\n\ntest('and() requires both rules', () => {\n  const catalog = new Catalog(SAMPLE_PRODUCTS);\n  expect(namesOf(catalog.find(new InCategory('books').and(new InStock())))).toEqual(['Clean Code']);\n});\n\ntest('or() accepts either rule and not() negates', () => {\n  const catalog = new Catalog(SAMPLE_PRODUCTS);\n  const booksOrGames = new InCategory('books').or(new InCategory('games'));\n  expect(namesOf(catalog.find(booksOrGames))).toEqual(['Clean Code', 'Refactoring', 'Catan', 'Chess Set']);\n  expect(namesOf(catalog.find(new InStock().not()))).toEqual(['Refactoring', 'Chess Set']);\n});\n\ntest('a weekly promotion is composed from small rules', () => {\n  const catalog = new Catalog(SAMPLE_PRODUCTS);\n  const promo = new InCategory('books').or(new InCategory('games')).and(new InStock()).and(new PriceAtMost(50));\n  expect(namesOf(catalog.find(promo))).toEqual(['Clean Code', 'Catan']);\n  expect(promo.isSatisfiedBy(SAMPLE_PRODUCTS[2])).toBe(true);\n  expect(promo.isSatisfiedBy(SAMPLE_PRODUCTS[5])).toBe(false);\n});\n\ntest('composition returns new specifications and leaves the parts untouched', () => {\n  const catalog = new Catalog(SAMPLE_PRODUCTS);\n  const cheap = new PriceAtMost(40);\n  const cheapBooks = cheap.and(new InCategory('books'));\n  expect(cheapBooks).toBeInstanceOf(CompositeSpecification);\n  expect(cheapBooks).not.toBe(cheap);\n  expect(namesOf(catalog.find(cheapBooks))).toEqual(['Clean Code']);\n  expect(namesOf(catalog.find(cheap))).toEqual(['Clean Code', 'Chess Set', 'USB Cable']);\n});\n\ntest('a custom rule plugs in without changing existing classes', () => {\n  class NameStartsWith extends CompositeSpecification {\n    constructor(prefix) {\n      super();\n      this.prefix = prefix;\n    }\n    isSatisfiedBy(product) {\n      return product.name.startsWith(this.prefix);\n    }\n  }\n  const catalog = new Catalog(SAMPLE_PRODUCTS);\n  const spec = new NameStartsWith('C').and(new InStock()).and(new InCategory('games').not());\n  expect(namesOf(catalog.find(spec))).toEqual(['Clean Code']);\n});\n\ntest('and() / or() short-circuit like && and ||', () => {\n  const spy = { calls: 0, isSatisfiedBy() { this.calls++; return true; } };\n  const [inStock, outOfStock] = SAMPLE_PRODUCTS;\n  expect(new InStock().and(spy).isSatisfiedBy(outOfStock)).toBe(false);\n  expect(new InStock().or(spy).isSatisfiedBy(inStock)).toBe(true);\n  expect(spy.calls).toBe(0);\n  expect(new InStock().and(spy).isSatisfiedBy(inStock)).toBe(true);\n  expect(spy.calls).toBe(1);\n});\n\ntest('Catalog keeps its order and is not changed through results', () => {\n  const catalog = new Catalog(SAMPLE_PRODUCTS);\n  const found = catalog.find(new InStock());\n  expect(namesOf(found)).toEqual(['Clean Code', 'Catan', 'USB Cable', 'Headphones']);\n  found.length = 0;\n  expect(catalog.count(new InStock())).toBe(4);\n  expect(catalog.count(new InCategory('toys'))).toBe(0);\n});\n"},{"lang":"javascript","runner":"browser","starter":"// Product: { name: string, category: string, price: number, stock: number }\n\n/**\n * Base class of every specification: concrete rules implement only isSatisfiedBy(candidate),\n * and(other), or(other) and not() are inherited and return new specifications.\n */\nclass CompositeSpecification {\n  isSatisfiedBy(candidate) {\n    throw new Error('isSatisfiedBy() must be implemented');\n  }\n\n  and(other) {\n    // TODO: a new specification satisfied when this AND other are satisfied\n    throw new Error('Not implemented');\n  }\n\n  or(other) {\n    // TODO: a new specification satisfied when this OR other is satisfied\n    throw new Error('Not implemented');\n  }\n\n  not() {\n    // TODO: a new specification satisfied when this one is NOT satisfied\n    throw new Error('Not implemented');\n  }\n}\n\n// TODO: AndSpecification, OrSpecification, NotSpecification (they extend CompositeSpecification too)\n\nclass InStock extends CompositeSpecification {\n  isSatisfiedBy(product) {\n    // TODO: stock > 0\n    throw new Error('Not implemented');\n  }\n}\n\nclass PriceAtMost extends CompositeSpecification {\n  constructor(max) {\n    super();\n    this.max = max;\n  }\n\n  isSatisfiedBy(product) {\n    // TODO: price <= max\n    throw new Error('Not implemented');\n  }\n}\n\nclass InCategory extends CompositeSpecification {\n  constructor(category) {\n    super();\n    this.category = category;\n  }\n\n  isSatisfiedBy(product) {\n    // TODO: exact category match\n    throw new Error('Not implemented');\n  }\n}\n\nclass Catalog {\n  constructor(products) {\n    this.products = products;\n  }\n\n  /** Products satisfying the specification, in catalog order. */\n  find(spec) {\n    throw new Error('Not implemented');\n  }\n\n  count(spec) {\n    throw new Error('Not implemented');\n  }\n}\n","testCount":8,"tests":"const SAMPLE_PRODUCTS = [\n  { name: 'Clean Code', category: 'books', price: 39, stock: 5 },\n  { name: 'Refactoring', category: 'books', price: 55, stock: 0 },\n  { name: 'Catan', category: 'games', price: 45, stock: 2 },\n  { name: 'Chess Set', category: 'games', price: 25, stock: 0 },\n  { name: 'USB Cable', category: 'electronics', price: 9, stock: 120 },\n  { name: 'Headphones', category: 'electronics', price: 199, stock: 7 },\n];\nconst namesOf = (products) => products.map((p) => p.name);\n\ntest('basic rules check a single product', () => {\n  const [cleanCode, refactoring] = SAMPLE_PRODUCTS;\n  expect(new InStock().isSatisfiedBy(cleanCode)).toBe(true);\n  expect(new InStock().isSatisfiedBy(refactoring)).toBe(false);\n  expect(new PriceAtMost(39).isSatisfiedBy(cleanCode)).toBe(true);\n  expect(new PriceAtMost(39).isSatisfiedBy(refactoring)).toBe(false);\n  expect(new InCategory('books').isSatisfiedBy(cleanCode)).toBe(true);\n  expect(new InCategory('games').isSatisfiedBy(cleanCode)).toBe(false);\n});\n\ntest('and() requires both rules', () => {\n  const catalog = new Catalog(SAMPLE_PRODUCTS);\n  expect(namesOf(catalog.find(new InCategory('books').and(new InStock())))).toEqual(['Clean Code']);\n});\n\ntest('or() accepts either rule and not() negates', () => {\n  const catalog = new Catalog(SAMPLE_PRODUCTS);\n  const booksOrGames = new InCategory('books').or(new InCategory('games'));\n  expect(namesOf(catalog.find(booksOrGames))).toEqual(['Clean Code', 'Refactoring', 'Catan', 'Chess Set']);\n  expect(namesOf(catalog.find(new InStock().not()))).toEqual(['Refactoring', 'Chess Set']);\n});\n\ntest('a weekly promotion is composed from small rules', () => {\n  const catalog = new Catalog(SAMPLE_PRODUCTS);\n  const promo = new InCategory('books').or(new InCategory('games')).and(new InStock()).and(new PriceAtMost(50));\n  expect(namesOf(catalog.find(promo))).toEqual(['Clean Code', 'Catan']);\n  expect(promo.isSatisfiedBy(SAMPLE_PRODUCTS[2])).toBe(true);\n  expect(promo.isSatisfiedBy(SAMPLE_PRODUCTS[5])).toBe(false);\n});\n\ntest('composition returns new specifications and leaves the parts untouched', () => {\n  const catalog = new Catalog(SAMPLE_PRODUCTS);\n  const cheap = new PriceAtMost(40);\n  const cheapBooks = cheap.and(new InCategory('books'));\n  expect(cheapBooks).toBeInstanceOf(CompositeSpecification);\n  expect(cheapBooks).not.toBe(cheap);\n  expect(namesOf(catalog.find(cheapBooks))).toEqual(['Clean Code']);\n  expect(namesOf(catalog.find(cheap))).toEqual(['Clean Code', 'Chess Set', 'USB Cable']);\n});\n\ntest('a custom rule plugs in without changing existing classes', () => {\n  class NameStartsWith extends CompositeSpecification {\n    constructor(prefix) {\n      super();\n      this.prefix = prefix;\n    }\n    isSatisfiedBy(product) {\n      return product.name.startsWith(this.prefix);\n    }\n  }\n  const catalog = new Catalog(SAMPLE_PRODUCTS);\n  const spec = new NameStartsWith('C').and(new InStock()).and(new InCategory('games').not());\n  expect(namesOf(catalog.find(spec))).toEqual(['Clean Code']);\n});\n\ntest('and() / or() short-circuit like && and ||', () => {\n  const spy = { calls: 0, isSatisfiedBy() { this.calls++; return true; } };\n  const [inStock, outOfStock] = SAMPLE_PRODUCTS;\n  expect(new InStock().and(spy).isSatisfiedBy(outOfStock)).toBe(false);\n  expect(new InStock().or(spy).isSatisfiedBy(inStock)).toBe(true);\n  expect(spy.calls).toBe(0);\n  expect(new InStock().and(spy).isSatisfiedBy(inStock)).toBe(true);\n  expect(spy.calls).toBe(1);\n});\n\ntest('Catalog keeps its order and is not changed through results', () => {\n  const catalog = new Catalog(SAMPLE_PRODUCTS);\n  const found = catalog.find(new InStock());\n  expect(namesOf(found)).toEqual(['Clean Code', 'Catan', 'USB Cable', 'Headphones']);\n  found.length = 0;\n  expect(catalog.count(new InStock())).toBe(4);\n  expect(catalog.count(new InCategory('toys'))).toBe(0);\n});\n"},{"lang":"python","runner":"browser","starter":"from abc import ABC, abstractmethod\nfrom dataclasses import dataclass\n\n\n@dataclass(frozen=True)\nclass Product:\n    name: str\n    category: str\n    price: float\n    stock: int\n\n\nclass Specification(ABC):\n    \"\"\"A business rule that can be checked against a candidate and combined with other rules.\"\"\"\n\n    @abstractmethod\n    def is_satisfied_by(self, candidate) -> bool: ...\n\n    def and_(self, other: \"Specification\") -> \"Specification\":\n        # TODO: a new specification satisfied when self AND other are satisfied\n        raise NotImplementedError\n\n    def or_(self, other: \"Specification\") -> \"Specification\":\n        # TODO: a new specification satisfied when self OR other is satisfied\n        raise NotImplementedError\n\n    def not_(self) -> \"Specification\":\n        # TODO: a new specification satisfied when self is NOT satisfied\n        raise NotImplementedError\n\n    # Operators: a & b, a | b, ~a\n    def __and__(self, other):\n        return self.and_(other)\n\n    def __or__(self, other):\n        return self.or_(other)\n\n    def __invert__(self):\n        return self.not_()\n\n\n# TODO: AndSpecification, OrSpecification, NotSpecification (subclasses of Specification)\n\n\nclass InStock(Specification):\n    def is_satisfied_by(self, product: Product) -> bool:\n        # TODO: stock > 0\n        raise NotImplementedError\n\n\nclass PriceAtMost(Specification):\n    def __init__(self, max_price: float):\n        self.max_price = max_price\n\n    def is_satisfied_by(self, product: Product) -> bool:\n        # TODO: price <= max_price\n        raise NotImplementedError\n\n\nclass InCategory(Specification):\n    def __init__(self, category: str):\n        self.category = category\n\n    def is_satisfied_by(self, product: Product) -> bool:\n        # TODO: exact category match\n        raise NotImplementedError\n\n\nclass Catalog:\n    def __init__(self, products: list[Product]):\n        self.products = products\n\n    def find(self, spec: Specification) -> list[Product]:\n        \"\"\"Products satisfying the specification, in catalog order.\"\"\"\n        raise NotImplementedError\n\n    def count(self, spec: Specification) -> int:\n        raise NotImplementedError\n","testCount":8,"tests":"SAMPLE_PRODUCTS = [\n    Product(\"Clean Code\", \"books\", 39, 5),\n    Product(\"Refactoring\", \"books\", 55, 0),\n    Product(\"Catan\", \"games\", 45, 2),\n    Product(\"Chess Set\", \"games\", 25, 0),\n    Product(\"USB Cable\", \"electronics\", 9, 120),\n    Product(\"Headphones\", \"electronics\", 199, 7),\n]\n\n\ndef names_of(products):\n    return [p.name for p in products]\n\n\ndef test_basic_rules_check_a_single_product():\n    clean_code, refactoring = SAMPLE_PRODUCTS[0], SAMPLE_PRODUCTS[1]\n    assert InStock().is_satisfied_by(clean_code) is True, \"Clean Code is in stock\"\n    assert InStock().is_satisfied_by(refactoring) is False, \"Refactoring is out of stock\"\n    assert PriceAtMost(39).is_satisfied_by(clean_code) is True, \"price 39 is at most 39\"\n    assert PriceAtMost(39).is_satisfied_by(refactoring) is False, \"price 55 is above 39\"\n    assert InCategory(\"books\").is_satisfied_by(clean_code) is True\n    assert InCategory(\"games\").is_satisfied_by(clean_code) is False\n\n\ndef test_and_requires_both_rules():\n    got = names_of(Catalog(SAMPLE_PRODUCTS).find(InCategory(\"books\").and_(InStock())))\n    assert got == [\"Clean Code\"], f\"expected ['Clean Code'], got {got}\"\n    got = names_of(Catalog(SAMPLE_PRODUCTS).find(InCategory(\"books\") & InStock()))\n    assert got == [\"Clean Code\"], f\"operator &: expected ['Clean Code'], got {got}\"\n\n\ndef test_or_accepts_either_rule_and_not_negates():\n    catalog = Catalog(SAMPLE_PRODUCTS)\n    got = names_of(catalog.find(InCategory(\"books\") | InCategory(\"games\")))\n    assert got == [\"Clean Code\", \"Refactoring\", \"Catan\", \"Chess Set\"], f\"got {got}\"\n    got = names_of(catalog.find(~InStock()))\n    assert got == [\"Refactoring\", \"Chess Set\"], f\"got {got}\"\n    got = names_of(catalog.find(InStock().not_()))\n    assert got == [\"Refactoring\", \"Chess Set\"], f\"not_(): got {got}\"\n\n\ndef test_a_weekly_promotion_is_composed_from_small_rules():\n    catalog = Catalog(SAMPLE_PRODUCTS)\n    promo = (InCategory(\"books\") | InCategory(\"games\")) & InStock() & PriceAtMost(50)\n    got = names_of(catalog.find(promo))\n    assert got == [\"Clean Code\", \"Catan\"], f\"expected ['Clean Code', 'Catan'], got {got}\"\n    assert promo.is_satisfied_by(SAMPLE_PRODUCTS[2]) is True\n    assert promo.is_satisfied_by(SAMPLE_PRODUCTS[5]) is False\n\n\ndef test_composition_returns_new_specifications_and_leaves_the_parts_untouched():\n    catalog = Catalog(SAMPLE_PRODUCTS)\n    cheap = PriceAtMost(40)\n    cheap_books = cheap & InCategory(\"books\")\n    assert isinstance(cheap_books, Specification), \"a combination is a Specification too\"\n    assert cheap_books is not cheap, \"and_() must return a new object\"\n    got = names_of(catalog.find(cheap_books))\n    assert got == [\"Clean Code\"], f\"got {got}\"\n    got = names_of(catalog.find(cheap))\n    assert got == [\"Clean Code\", \"Chess Set\", \"USB Cable\"], f\"the original rule changed: {got}\"\n\n\ndef test_a_custom_rule_plugs_in_without_changing_existing_classes():\n    class NameStartsWith(Specification):\n        def __init__(self, prefix):\n            self.prefix = prefix\n\n        def is_satisfied_by(self, product):\n            return product.name.startswith(self.prefix)\n\n    spec = NameStartsWith(\"C\") & InStock() & ~InCategory(\"games\")\n    got = names_of(Catalog(SAMPLE_PRODUCTS).find(spec))\n    assert got == [\"Clean Code\"], f\"expected ['Clean Code'], got {got}\"\n\n\ndef test_and_or_short_circuit():\n    class Spy(Specification):\n        calls = 0\n\n        def is_satisfied_by(self, candidate):\n            self.calls += 1\n            return True\n\n    spy = Spy()\n    in_stock, out_of_stock = SAMPLE_PRODUCTS[0], SAMPLE_PRODUCTS[1]\n    assert (InStock() & spy).is_satisfied_by(out_of_stock) is False\n    assert (InStock() | spy).is_satisfied_by(in_stock) is True\n    assert spy.calls == 0, f\"the right rule must not be evaluated, it was called {spy.calls} times\"\n    assert (InStock() & spy).is_satisfied_by(in_stock) is True\n    assert spy.calls == 1, f\"expected 1 call, got {spy.calls}\"\n\n\ndef test_catalog_keeps_its_order_and_is_not_changed_through_results():\n    catalog = Catalog(SAMPLE_PRODUCTS)\n    found = catalog.find(InStock())\n    got = names_of(found)\n    assert got == [\"Clean Code\", \"Catan\", \"USB Cable\", \"Headphones\"], f\"got {got}\"\n    found.clear()\n    assert catalog.count(InStock()) == 4, \"clearing the result list must not change the catalog\"\n    assert catalog.count(InCategory(\"toys\")) == 0\n"},{"lang":"csharp","runner":"judge0","starter":"using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Product\n{\n    public Product(string name, string category, decimal price, int stock)\n    {\n        Name = name;\n        Category = category;\n        Price = price;\n        Stock = stock;\n    }\n\n    public string Name { get; private set; }\n    public string Category { get; private set; }\n    public decimal Price { get; private set; }\n    public int Stock { get; private set; }\n}\n\n/// <summary>A business rule checked against a candidate.</summary>\npublic interface ISpecification<T>\n{\n    bool IsSatisfiedBy(T candidate);\n}\n\n/// <summary>Base class: concrete rules implement only IsSatisfiedBy, composition is inherited.</summary>\npublic abstract class Specification<T> : ISpecification<T>\n{\n    public abstract bool IsSatisfiedBy(T candidate);\n\n    public Specification<T> And(ISpecification<T> other)\n    {\n        // TODO: a new specification satisfied when this AND other are satisfied\n        throw new NotImplementedException();\n    }\n\n    public Specification<T> Or(ISpecification<T> other)\n    {\n        // TODO: a new specification satisfied when this OR other is satisfied\n        throw new NotImplementedException();\n    }\n\n    public Specification<T> Not()\n    {\n        // TODO: a new specification satisfied when this one is NOT satisfied\n        throw new NotImplementedException();\n    }\n}\n\n// TODO: AndSpecification<T>, OrSpecification<T>, NotSpecification<T>\n\npublic class InStock : Specification<Product>\n{\n    public override bool IsSatisfiedBy(Product product)\n    {\n        // TODO: Stock > 0\n        throw new NotImplementedException();\n    }\n}\n\npublic class PriceAtMost : Specification<Product>\n{\n    private readonly decimal max;\n\n    public PriceAtMost(decimal max)\n    {\n        this.max = max;\n    }\n\n    public override bool IsSatisfiedBy(Product product)\n    {\n        // TODO: Price <= max\n        throw new NotImplementedException();\n    }\n}\n\npublic class InCategory : Specification<Product>\n{\n    private readonly string category;\n\n    public InCategory(string category)\n    {\n        this.category = category;\n    }\n\n    public override bool IsSatisfiedBy(Product product)\n    {\n        // TODO: exact category match\n        throw new NotImplementedException();\n    }\n}\n\npublic class Catalog\n{\n    private readonly List<Product> products;\n\n    public Catalog(IEnumerable<Product> products)\n    {\n        this.products = products.ToList();\n    }\n\n    /// <summary>Products satisfying the specification, in catalog order.</summary>\n    public IReadOnlyList<Product> Find(ISpecification<Product> spec)\n    {\n        throw new NotImplementedException();\n    }\n\n    public int Count(ISpecification<Product> spec)\n    {\n        throw new NotImplementedException();\n    }\n}\n","testCount":8},{"lang":"java","runner":"judge0","starter":"import java.util.ArrayList;\nimport java.util.List;\n\nclass Product {\n    private final String name;\n    private final String category;\n    private final double price;\n    private final int stock;\n\n    Product(String name, String category, double price, int stock) {\n        this.name = name;\n        this.category = category;\n        this.price = price;\n        this.stock = stock;\n    }\n\n    String getName() { return name; }\n    String getCategory() { return category; }\n    double getPrice() { return price; }\n    int getStock() { return stock; }\n}\n\n/** A business rule. One abstract method, so a lambda is a specification too. */\ninterface Specification<T> {\n    boolean isSatisfiedBy(T candidate);\n\n    default Specification<T> and(Specification<T> other) {\n        // TODO: a new specification satisfied when this AND other are satisfied\n        throw new UnsupportedOperationException(\"Not implemented\");\n    }\n\n    default Specification<T> or(Specification<T> other) {\n        // TODO: a new specification satisfied when this OR other is satisfied\n        throw new UnsupportedOperationException(\"Not implemented\");\n    }\n\n    default Specification<T> not() {\n        // TODO: a new specification satisfied when this one is NOT satisfied\n        throw new UnsupportedOperationException(\"Not implemented\");\n    }\n}\n\nclass InStock implements Specification<Product> {\n    @Override\n    public boolean isSatisfiedBy(Product product) {\n        // TODO: stock > 0\n        throw new UnsupportedOperationException(\"Not implemented\");\n    }\n}\n\nclass PriceAtMost implements Specification<Product> {\n    private final double max;\n\n    PriceAtMost(double max) { this.max = max; }\n\n    @Override\n    public boolean isSatisfiedBy(Product product) {\n        // TODO: price <= max\n        throw new UnsupportedOperationException(\"Not implemented\");\n    }\n}\n\nclass InCategory implements Specification<Product> {\n    private final String category;\n\n    InCategory(String category) { this.category = category; }\n\n    @Override\n    public boolean isSatisfiedBy(Product product) {\n        // TODO: exact category match\n        throw new UnsupportedOperationException(\"Not implemented\");\n    }\n}\n\nclass Catalog {\n    private final List<Product> products;\n\n    Catalog(List<Product> products) { this.products = new ArrayList<>(products); }\n\n    /** Products satisfying the specification, in catalog order. */\n    List<Product> find(Specification<Product> spec) {\n        throw new UnsupportedOperationException(\"Not implemented\");\n    }\n\n    int count(Specification<Product> spec) {\n        throw new UnsupportedOperationException(\"Not implemented\");\n    }\n}\n","testCount":8},{"lang":"go","runner":"judge0","starter":"package main\n\n// Product is an item of the shop catalog.\ntype Product struct {\n\tName     string\n\tCategory string\n\tPrice    float64\n\tStock    int\n}\n\n// Specification is a business rule checked against a product.\ntype Specification interface {\n\tIsSatisfiedBy(p Product) bool\n}\n\n// SpecFunc adapts an ordinary function to Specification (like http.HandlerFunc).\ntype SpecFunc func(p Product) bool\n\n// IsSatisfiedBy calls f(p).\nfunc (f SpecFunc) IsSatisfiedBy(p Product) bool { return f(p) }\n\n// And returns a new specification satisfied when left AND right are satisfied.\nfunc And(left, right Specification) Specification {\n\t// TODO\n\treturn nil\n}\n\n// Or returns a new specification satisfied when left OR right is satisfied.\nfunc Or(left, right Specification) Specification {\n\t// TODO\n\treturn nil\n}\n\n// Not returns a new specification satisfied when spec is NOT satisfied.\nfunc Not(spec Specification) Specification {\n\t// TODO\n\treturn nil\n}\n\n// InStock: Stock > 0.\ntype InStock struct{}\n\n// IsSatisfiedBy implements Specification.\nfunc (InStock) IsSatisfiedBy(p Product) bool {\n\t// TODO\n\treturn false\n}\n\n// PriceAtMost: Price <= Max.\ntype PriceAtMost struct{ Max float64 }\n\n// IsSatisfiedBy implements Specification.\nfunc (s PriceAtMost) IsSatisfiedBy(p Product) bool {\n\t// TODO\n\treturn false\n}\n\n// InCategory: exact category match.\ntype InCategory struct{ Category string }\n\n// IsSatisfiedBy implements Specification.\nfunc (s InCategory) IsSatisfiedBy(p Product) bool {\n\t// TODO\n\treturn false\n}\n\n// Catalog keeps products and finds those satisfying a specification.\ntype Catalog struct {\n\tproducts []Product\n}\n\n// NewCatalog copies the given products.\nfunc NewCatalog(products []Product) *Catalog {\n\treturn &Catalog{products: append([]Product(nil), products...)}\n}\n\n// Find returns products satisfying spec, in catalog order.\nfunc (c *Catalog) Find(spec Specification) []Product {\n\t// TODO\n\treturn nil\n}\n\n// Count returns how many products satisfy spec.\nfunc (c *Catalog) Count(spec Specification) int {\n\t// TODO\n\treturn -1\n}\n","testCount":8}],"questionCount":null,"xp":20,"stats":{"attempts":0,"solves":0,"solutions":0,"comments":0},"solveRate":null,"publishedAt":"2026-11-27T08:22:24.795Z","requestedLang":"pl","statement":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Dział marketingu co tydzień zmienia reguły promocji: raz „książki lub gry, dostępne, do 50 zł”, za tydzień „elektronika, ale bez akcesoriów”. Dotąd każda kampania kończyła się nową metodą "},{"type":"text","text":"findPromoProducts2()","marks":[{"type":"code"}]},{"type":"text","text":" z coraz dłuższym "},{"type":"text","text":"if","marks":[{"type":"code"}]},{"type":"text","text":". Pora na "},{"type":"text","text":"Specyfikację","marks":[{"type":"bold"}]},{"type":"text","text":" (ang. "},{"type":"text","text":"Specification","marks":[{"type":"italic"}]},{"type":"text","text":", Eric Evans i Martin Fowler): każda reguła biznesowa to osobny obiekt z metodą "},{"type":"text","text":"isSatisfiedBy(candidate)","marks":[{"type":"code"}]},{"type":"text","text":", a złożone warunki powstają z małych reguł łączonych przez "},{"type":"text","text":"and","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"or","marks":[{"type":"code"}]},{"type":"text","text":" i "},{"type":"text","text":"not","marks":[{"type":"code"}]},{"type":"text","text":"."}]},{"type":"heading","attrs":{"level":2,"id":"zadanie"},"content":[{"type":"text","text":"Zadanie"}]},{"type":"orderedList","attrs":{"start":1},"content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Kombinatory","marks":[{"type":"bold"}]},{"type":"text","text":" w klasie bazowej: "},{"type":"text","text":"and(other)","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"or(other)","marks":[{"type":"code"}]},{"type":"text","text":" i "},{"type":"text","text":"not()","marks":[{"type":"code"}]},{"type":"text","text":". Każdy zwraca "},{"type":"text","text":"nową","marks":[{"type":"bold"}]},{"type":"text","text":" specyfikację, którą znów można łączyć – oryginalne reguły się nie zmieniają."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"and","marks":[{"type":"code"}]},{"type":"text","text":" i "},{"type":"text","text":"or","marks":[{"type":"code"}]},{"type":"text","text":" "},{"type":"text","text":"skracają obliczenia","marks":[{"type":"bold"}]},{"type":"text","text":" jak "},{"type":"text","text":"&&","marks":[{"type":"code"}]},{"type":"text","text":" i "},{"type":"text","text":"||","marks":[{"type":"code"}]},{"type":"text","text":": prawa reguła nie jest sprawdzana, gdy wynik przesądza już lewa."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Reguły","marks":[{"type":"bold"}]},{"type":"text","text":": "},{"type":"text","text":"InStock","marks":[{"type":"code"}]},{"type":"text","text":" (stan magazynowy większy od zera), "},{"type":"text","text":"PriceAtMost(max)","marks":[{"type":"code"}]},{"type":"text","text":" (cena nie większa niż "},{"type":"text","text":"max","marks":[{"type":"code"}]},{"type":"text","text":"), "},{"type":"text","text":"InCategory(category)","marks":[{"type":"code"}]},{"type":"text","text":" (dokładnie ta kategoria)."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Katalog","marks":[{"type":"bold"}]},{"type":"text","text":": "},{"type":"text","text":"Catalog.find(spec)","marks":[{"type":"code"}]},{"type":"text","text":" zwraca produkty spełniające specyfikację w kolejności katalogu, a "},{"type":"text","text":"count(spec)","marks":[{"type":"code"}]},{"type":"text","text":" – ich liczbę. Zmiana listy przekazanej do konstruktora ani zwróconego wyniku nie może zmienić zawartości katalogu."}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"Przykładowa promocja: "},{"type":"text","text":"InCategory('books').or(InCategory('games')).and(InStock()).and(PriceAtMost(50))","marks":[{"type":"code"}]},{"type":"text","text":" – w danych testowych spełniają ją tylko „Clean Code” i „Catan”."}]},{"type":"paragraph","content":[{"type":"text","text":"Kombinatory w poszczególnych językach:"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"TypeScript / JavaScript","marks":[{"type":"bold"}]},{"type":"text","text":" – metody "},{"type":"text","text":"a.and(b)","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"a.or(b)","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"a.not()","marks":[{"type":"code"}]},{"type":"text","text":" w klasie "},{"type":"text","text":"CompositeSpecification","marks":[{"type":"code"}]},{"type":"text","text":"; testy dopisują własną regułę jako jej podklasę."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Python","marks":[{"type":"bold"}]},{"type":"text","text":" – metody "},{"type":"text","text":"and_","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"or_","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"not_","marks":[{"type":"code"}]},{"type":"text","text":" w klasie "},{"type":"text","text":"Specification","marks":[{"type":"code"}]},{"type":"text","text":" (operatory "},{"type":"text","text":"&","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"|","marks":[{"type":"code"}]},{"type":"text","text":" i "},{"type":"text","text":"~","marks":[{"type":"code"}]},{"type":"text","text":" są już gotowe i z nich korzystają)."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"C#","marks":[{"type":"bold"}]},{"type":"text","text":" – "},{"type":"text","text":"And","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"Or","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"Not","marks":[{"type":"code"}]},{"type":"text","text":" w klasie abstrakcyjnej "},{"type":"text","text":"Specification<T>","marks":[{"type":"code"}]},{"type":"text","text":", przyjmujące "},{"type":"text","text":"ISpecification<T>","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Java","marks":[{"type":"bold"}]},{"type":"text","text":" – metody domyślne interfejsu "},{"type":"text","text":"Specification<T>","marks":[{"type":"code"}]},{"type":"text","text":"; ma on jedną metodę abstrakcyjną, więc testy tworzą reguły także lambdami."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Go","marks":[{"type":"bold"}]},{"type":"text","text":" – funkcje "},{"type":"text","text":"And(a, b)","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"Or(a, b)","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"Not(a)","marks":[{"type":"code"}]},{"type":"text","text":" oraz typ "},{"type":"text","text":"SpecFunc","marks":[{"type":"code"}]},{"type":"text","text":", który zamienia zwykłą funkcję w specyfikację."}]}]}]},{"type":"callout","attrs":{"variant":"tip","title":"Po co to wszystko?"},"content":[{"type":"paragraph","content":[{"type":"text","text":"Ta sama specyfikacja filtruje listę, sprawdza pojedynczy produkt („czy może wejść do promocji?”), a w prawdziwym systemie bywa tłumaczona na zapytanie do bazy. Nowa reguła to nowa, mała klasa – bez zmian w katalogu i w istniejących regułach."}]}]}]},"hints":[],"hintsCount":3,"quiz":null,"solutionNotes":null,"unlocked":false,"external":[],"articles":[{"id":"6b093dc091bd8fbaf2a0c8b2","slug":"specification","title":"Specyfikacja: reguły biznesowe jako obiekty, które się składa"}],"topicsInfo":[{"slug":"specification","title":"Specyfikacja (Specification)","group":"architecture","icon":"list-filter"}],"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"capabilities":{"judge0":false,"aiReview":false},"createdAt":"2026-11-27T08:22:24.797Z","updatedAt":"2026-11-27T08:22:24.797Z"}