Wow
Wow

Reputation: 305

What's the better coding style in oop: one method with one parameter VS two methods without parameters?

What's the better way for clean code from the oop point of view? Having two related methods with different names or one common method with an extra parameter?

(Simplified) Example:

1.) public void LogError() { ... } public void LogWarning() { ... }

VS

2.) public void Log(LogType logType) { ... } //LogType.Error vs LogType.Warning

Upvotes: 1

Views: 202

Answers (1)

T.Nylund
T.Nylund

Reputation: 787

Both are good choices. Maybe a few examples can make it more clear. Usually, I try to think who is gonna use the library (me or someone else) and what programming language I use.

For example:

If I use strongly typed language like Java, C#, etc then I prefer choice 2.

If I use something else like PHP or Python, then I prefer choice 1.

If I want to make a simplified interface for other developers that are gonna use my library, for example, then I prefer choice 1 too.

When you have LogType enum for example, then it really doesn’t matter. Just try to think about how to describe the intent and make it clear.

Watch out boolean parameters that can be confusing many times. For example:

public void SaveProduct(bool cache) { ... }

In those situations, choice 1 is usually better because it can be very hard to understand what boolean values do. (How it changes the behavior) Also, it usually tells that the method is doing two different actions so possibly there is a way to refactor it. For example, splitting it into two methods and then the developer does not need to know about the implementation details.

Upvotes: 2

Related Questions