The scene of a

Sometimes we’ll come across a method that fills the screen with if else, for loops, and a, B, and C arguments, and it’s really confusing. Let the back of the maintenance of people back, but also the real code block to continue to increase, increase…… When we look at such code, fortunately I do not have to maintain, pit dad things need to change their own, the heart has been ten thousand grass nimah drift.

Scenario 2

When some beginners learn to touch design patterns, it feels like they are looking at martial arts secrets. Without thinking directly online set, all kinds of factory mode, strategy mode, decoration mode and so on, will appear more bloated, too many classes. A simple function can be overdesigned.

How can we as Java novices avoid this

I came across a blog by Mark Seemann about The 80/24 Rule and it was very enlightening. The 80/24 rule refers to the blocks of code we write (no more than 24 lines of 80 characters per line) and you can refer to the link for more details. With rules like this, it’s easy to get rid of some bad code smells. Such as:

  • Duplicate code
  • Too long function method
  • Too much class
  • Too long parameter column
  • , etc.

Use small, beautiful blocks of code

Small code blocks, small methods, small functions, small procedures, with small and beautiful code to decorate our software. How to achieve small and beautiful blocks of code have the following concerns

  • Number of characters per line: <80
  • Method body line number: <24
  • Method dependency (object or method) : <7
  • Complexity of loop nesting in code block: <3

Elegant code examples

public ActionResult Post(ReservationDto dto)
{
    var validationMsg = Validator.Validate(dto);
    if(validationMsg ! ="")
        return BadRequest(validationMsg);
 
    var reservation = Mapper.Map(dto);
    var reservations = Repository.ReadReservations(reservation.Date);
 
    varAccepted = maitreD. CanAccept (reservations, reservation);if(! accepted)return StatusCode(
            StatusCodes.Status500InternalServerError,
            "Couldn't accept.");
 
    var id = Repository.Create(reservation);
    return Ok(id);
}
Copy the code
  • Do not have parameters that are irrelevant to the business

  • Avoid complex objects such as maps and Json as parameters and results

  • There are explicit input, output and method names

  • Write functions that can be tested

The article has helped you, please pay attention to the wechat public number: wanton dissociation has more wonderful waiting for you