Conditions | 10 |
Total Lines | 52 |
Code Lines | 33 |
Lines | 0 |
Ratio | 0 % |
Changes | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
Complex classes like postgres.New often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
1 | package postgres |
||
30 | func New(uri string, opts ...Option) (*Postgres, error) { |
||
31 | pg := &Postgres{ |
||
32 | maxOpenConnections: _defaultMaxOpenConnections, |
||
33 | maxIdleConnections: _defaultMaxIdleConnections, |
||
34 | maxDataPerWrite: _defaultMaxDataPerWrite, |
||
35 | maxRetries: _defaultMaxRetries, |
||
36 | watchBufferSize: _defaultWatchBufferSize, |
||
37 | } |
||
38 | |||
39 | // Custom options |
||
40 | for _, opt := range opts { |
||
41 | opt(pg) |
||
42 | } |
||
43 | |||
44 | pg.Builder = squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar) |
||
45 | |||
46 | db, err := sql.Open("pgx", uri) |
||
47 | if err != nil { |
||
48 | return nil, err |
||
49 | } |
||
50 | |||
51 | if pg.maxOpenConnections != 0 { |
||
52 | db.SetMaxOpenConns(pg.maxOpenConnections) |
||
53 | } |
||
54 | |||
55 | if pg.maxIdleConnections != 0 { |
||
56 | db.SetMaxIdleConns(pg.maxIdleConnections) |
||
57 | } |
||
58 | |||
59 | if pg.maxConnectionLifeTime != 0 { |
||
60 | db.SetConnMaxLifetime(pg.maxConnectionLifeTime) |
||
61 | } |
||
62 | |||
63 | if pg.maxConnectionIdleTime != 0 { |
||
64 | db.SetConnMaxIdleTime(pg.maxConnectionIdleTime) |
||
65 | } |
||
66 | |||
67 | policy := backoff.NewExponentialBackOff() |
||
68 | policy.MaxElapsedTime = 1 * time.Minute |
||
69 | err = backoff.Retry(func() error { |
||
70 | err = db.PingContext(context.Background()) |
||
71 | if err != nil { |
||
72 | return err |
||
73 | } |
||
74 | return nil |
||
75 | }, policy) |
||
76 | if err != nil { |
||
77 | return nil, err |
||
78 | } |
||
79 | |||
80 | pg.DB = db |
||
81 | return pg, nil |
||
82 | } |
||
118 |