Methods should solve a single problem, answer a single question, or otherwise do one thing.
When you, the author, are asked “what is this code going to do ?” you should be able to say it in ONE sentence without the use of conjunctions or disjunctions – no ANDs and ORs required.
The upside to such a description is that this often can make method nice and short. A “page” of code or less so its easy to read and see that the stated purpose is met.
As well you should be able to avoid side effects as the code answers the one question its asked, or solves the one purpose its started to solve (esp if you adhere to the Law Of Demeter)
What do I mean by all this ?
Often in code you have a need to know IF some variable contains a value that IS representative of some kind of data. Is the value in a string a date, an email address, a url your code knows how to handle, an integer, a floating point value, a boolean etc.
In one bit of code I’m working on there are strings that may hold one of several types of data. And we need to know what data type that data is. So there is code like the following to examine the value and decide what kind of value this is
Select Case True Case value.Left(1) = """" And value.Right(1) = """" type = "String" Case IsInteger(value) type = "Integer" Case IsRealNumber(value) type = "Double" Case value = "True" Or value = "False" type = "Boolean" Case value.Left(2) = "&c" type = "Color" Case value.Left(2) = "&h" type = "Uinteger" End Select End If
The calls to IsInteger and IsRealNumber examine the passed parameter and return a true false value. And do NO more than that. They do not alter the value as that could cause side effects in other code.
When you write code that does more than answer the question asked you can cause yourself unnecessary work. How so ? Imagine that the IsInteger call above actually altered the value passed in. I would need an extra variable to make a copy of that value before calling it.
As well, its not obvious that this IsInteger method WILL alter the value passed in just by reading the code. At the time you write this code you will probably remember it. But in 6 months you won’t. Nor would someone else reading the code expect that should happen.
Dont do it to yourself or to your team mates.
If you have an IsX method then you probably also need a “ConvertToX” method. So for the example above IF some data can be determined to BE suitable for an integer then a “ConvertToInteger” method would make perfect sense.
Don’t do them in one step and don’t alter the data your given (ie/ do not use a byref parameter and alter the original data)
You future self will like your code a lot more.