Design Patterns Handbook
  • Introduction
  • Creational Patterns
    • Builder
    • Factory
    • Abstract Factory
    • Factory Method
    • Prototype
    • Singleton
    • Object Pool
    • Revealing Constructor
  • Structural Patterns
    • Adapter
    • Composite
    • Proxy
    • Flyweight
    • Facade
    • Bridge
    • Decorator
    • Private Class Data
  • Behavioral Patterns
    • Template Method
    • Mediator
    • Chain Of Responsibility
    • Observer
    • Strategy
    • Command
    • State
    • Visitor
    • Memento
    • Interpreter
    • Null Object
    • Iterator
    • Middleware
  • Clean Code Patterns
    • Extract Method
    • Clarify Responsibility
    • Remove Duplications
    • Keep Refactoring
    • Always Unit Test
    • Create Data Type
    • Comment to Better Name
    • Consistent Naming
    • If-else over ternary operator
    • Composition over Inheritance
    • Too Many Returns
    • Private to Interface
  • Anti Patterns
    • Big Ball of Mud
    • Singleton
    • Mad Scientist
    • Spaghetti Code
    • It Will Never Happen
    • Error Codes
    • Commented Code
    • Abbreviations
    • Prefixes
    • Over Patternized
    • Generic Interface over Function
Powered by GitBook
On this page

Was this helpful?

  1. Clean Code Patterns

If-else over ternary operator

We need to avoid very long lines that are using ternary operator, because it makes code very difficult to read.

Straightforward usage of ternary operator is OK, for example: String name = user ? user.getName() : "";

Here is an example, last line in a controller that decides what is going to be returned.

return result != null ? ResponseEntity.ok(result).header("Location", "/v1/task/" + result.getId()).build() : Response.status(Status.BAD_REQUEST).header("ErrorMessage", "Invalid taskdata").build();

What if we want to refactor such a code? We first split it into if-else branches and then we figure out what is actually happening.

PreviousConsistent NamingNextComposition over Inheritance

Last updated 5 years ago

Was this helpful?