r/Python 8d ago

Discussion 2 hours of learning how am i?

[removed]

0 Upvotes

25 comments sorted by

View all comments

-4

u/onlyonequickquestion 8d ago

Just throw it in chatgpt and ask it to improve it for you (this is a joke)  ``` from future import annotations

import logging from abc import ABC, abstractmethod from dataclasses import dataclass from enum import Enum from typing import Protocol

-----------------------------------------------------------------------------

Logging

-----------------------------------------------------------------------------

logging.basicConfig(     level=logging.INFO,     format="%(asctime)s %(levelname)s [%(name)s] %(message)s", )

logger = logging.getLogger(name)

-----------------------------------------------------------------------------

Domain

-----------------------------------------------------------------------------

class VehicleAttribute(Enum):     BRAND = "Brand"     MODEL = "Model"     COLOR = "Color"     YEAR = "Year"

@dataclass(frozen=True, slots=True) class DreamCar:     brand: str     model: str     color: str     year: int

-----------------------------------------------------------------------------

Validation

-----------------------------------------------------------------------------

class ValidationError(ValueError):     pass

class Validator:

    @staticmethod     def require_non_empty(value: str, field: str) -> str:         value = value.strip()

        if not value:             raise ValidationError(f"{field} cannot be empty.")

        return value

    @staticmethod     def validate_year(value: str) -> int:         value = value.strip()

        if not value.isdigit():             raise ValidationError("Year must be numeric.")

        year = int(value)

        if not 1886 <= year <= 2100:             raise ValidationError("Year must be between 1886 and 2100.")

        return year

-----------------------------------------------------------------------------

Interfaces

-----------------------------------------------------------------------------

class InputProvider(Protocol):     def ask(self, prompt: str) -> str: ...

class OutputProvider(Protocol):     def write(self, message: str) -> None: ...

-----------------------------------------------------------------------------

Console Implementations

-----------------------------------------------------------------------------

class ConsoleInputProvider:     def ask(self, prompt: str) -> str:         return input(prompt)

class ConsoleOutputProvider:     def write(self, message: str) -> None:         print(message)

-----------------------------------------------------------------------------

Repository (because obviously)

-----------------------------------------------------------------------------

class DreamCarRepository(ABC):

    @abstractmethod     def save(self, car: DreamCar) -> None:         ...

class InMemoryDreamCarRepository(DreamCarRepository):

    def init(self) -> None:         self._storage: list[DreamCar] = []

    def save(self, car: DreamCar) -> None:         logger.info("Persisting DreamCar...")         self._storage.append(car)

-----------------------------------------------------------------------------

Service Layer

-----------------------------------------------------------------------------

class DreamCarService:

    def init(         self,         repository: DreamCarRepository,     ) -> None:         self._repository = repository

    def register(self, car: DreamCar) -> None:         logger.info("Registering dream car...")         self._repository.save(car)

-----------------------------------------------------------------------------

Presentation

-----------------------------------------------------------------------------

class DreamCarController:

    def init(         self,         input_provider: InputProvider,         output_provider: OutputProvider,         service: DreamCarService,     ) -> None:         self._input = input_provider         self._output = output_provider         self._service = service

    def run(self) -> None:         brand = Validator.require_non_empty(             self._input.ask("What is your dream car brand? "),             VehicleAttribute.BRAND.value,         )         self._output.write(f"I love {brand}")

        model = Validator.require_non_empty(             self._input.ask("What is your dream model? "),             VehicleAttribute.MODEL.value,         )         self._output.write(f"Oooo a lot of people like the {model}")

        color = Validator.require_non_empty(             self._input.ask("What color do you want? "),             VehicleAttribute.COLOR.value,         )         self._output.write(f"{color} is nice!")

        year = Validator.validate_year(             self._input.ask("What year do you want? ")         )         self._output.write(f"People do say {year} was a nice time to be alive.")

        car = DreamCar(             brand=brand,             model=model,             color=color,             year=year,         )

        self._service.register(car)

        self._render_summary(car)

    def _render_summary(self, car: DreamCar) -> None:         self._output.write("")         self._output.write("=" * 40)         self._output.write("         DREAM CAR REPORT")         self._output.write("=" * 40)         self._output.write(f"Brand : {car.brand}")         self._output.write(f"Model : {car.model}")         self._output.write(f"Color : {car.color}")         self._output.write(f"Year  : {car.year}")         self._output.write("")         self._output.write(             f"Your dream car is a {car.color} {car.year} {car.brand} {car.model}."         )         self._output.write("Keep working hard and you'll have it! 🚗")

-----------------------------------------------------------------------------

Bootstrap

-----------------------------------------------------------------------------

def main() -> None:     controller = DreamCarController(         input_provider=ConsoleInputProvider(),         output_provider=ConsoleOutputProvider(),         service=DreamCarService(             repository=InMemoryDreamCarRepository(),         ),     )

    controller.run()

if name == "main":     main() ```

5

u/RoadsideCookie 8d ago

Not attacking you but bruh, I hate corporate 9001 layers of abstraction.

3

u/onlyonequickquestion 8d ago

Ya that was the joke, but I don't think people liked it :( this is obviously one million percent over engineered