|
Tech forum
The Power of the DOT
Article Summary
This article provides a new way of looking at functionality
available in .NET and provides practical guidelines for finding the right thing
in the right place. Following these tips will simplify coding effort substantially.
The apparently insignificant ‘.’ in the .NET
name is actually very, very powerful. In fact if you respect and use the dot
effectively, it will change the way you translate functionality into efficient
code. Read on to find out how.
Life without the DOT
In any kind of programming, the core task is to perform operations
on (or involving) data. For example, you calculate the square root of a number,
find the length of a string, find the difference between two dates, or store
contact information to a database. The exact way this has been done, traditionally,
is a major subject of discussion in computer science. Several approaches have
come up. The one that most of us are used to is called the ‘imperative
programming’ approach.
In this approach, the programming language provides features
which act on the data, and produce results. Let us observe an example, using
the Visual Basic language.
Rootvalue = Sqrt(4)
Namelength = Len(“Madangere Venkatswamy Subramanian”)
Write #1, ContactName, ContactPhoneNumber,
ContactAddress
Difference = #13-Jan-2004# – #2-Nov-1973#
In the first two lines, we use a language feature called functions
to act on data. “Sqrt” and “Len” are functions which
calculate the square root of a number and the length of a string respectively,
and are provided by the Visual Basic language. In the third case, a statement
called Write is being used to write some data to a file. The statement is provided
by the Visual Basic language. In the fourth case, one date is subtracted from
another, and the difference is being returned as a number. This, once again,
is a feature of the Visual Basic language.
What if we use another language? For most programming languages
that people are familiar with, the concept does not change. The syntax will.
In fact, some languages provide only functions. Others have different statements,
or give different meaning to operations like subtraction. But the base idea
of applying operations to data remains the same.
Object-oriented design
For several years now, we have been moving away from the
imperative approach, and towards the approach termed ‘object-oriented’.
In this approach, we do not look at operations and data as separate. Instead,
we look at distinct entities called objects, which consist of data, but also
define operations that can be performed on that data. In programming, therefore,
we do not apply statements or functions to data. Instead, we take an instance
of a object, and call a method on it.
The design of .NET
The
key feature of .NET platform is that everything is designed as a set of generic
classes and leading to specific subclasses. For example, everything in .NET
originates with the class called Object. As per definition, an instance of a
class is called an object. However, in this case the class itself is called
“Object”. Let this not confuse you.
Under the Microsoft .NET Framework, there are many languages,
and all of them are expected to understand the concept of objects. The complete
functionality of the .NET Framework is exposed as a massive set of objects (or
classes) called the .NET Framework Class Library. Everything under the .NET
Framework is an object, including numbers, dates, strings, controls, windows,
network, WMI, database, cryptography and so on. Thus, any operation is ultimately
a method of some object or the other.
Now, while all other classes were being derived, additional
thought was given to the functionality required at the level of each subclass.
For example, consider strings. As shown above, if you want to manipulate strings,
you would typically require functions. These functions like LEN, MID, RIGHT,
INSTR are still retained in VB.NET for backward compatibility. But there is
a better way – a much better way.
Rather than using a function on a string, we must now understand
that any string is now an OBJECT of the STRING class. Therefore, like all objects
it has properties and methods. How do you know these properties and methods
and additional functionality.
The answer is simple – The power of the DOT.
Simple. Declare a string variable. Assign a value to it.
Now let us say, you want to perform the same operation of finding the length
of the string. All that you have to do is to create a string object, assign
value to it and press the all powerful DOT.
Same way, here is how we could write it without explicitly
defining the string variable. We are directly using a string value itself! Fast,
Efficient, Intuitive and Simple.
NameLength = “Madangere Venkatswamy
Subramanian”.Length()
We are asking the string itself for its length.
Here is an example which is equivalent to & operator
used for concatenation. Here is the object oriented version of concatenation.
Dim s1 as string, s2 as string, s3 as string
s2= “This is the first piece.”
s3 = “This is the second piece.”
s1= string.concat(s2, s3)
Here notice that the concatenation is done by a shared method
(method available at class level, not instance level) of the string class called
concat.
As
string manipulation is done very commonly, here is the list of things that are
available in the string object itself.
Best Practice - Search
- What is the target object?
- What do you want to do to the object?
- Is that functionality already available as a language
level command or function?
- If yes or If no, in either case, try to search for a similar
Object level functionality.
- Now find the difference in the functionality. Sometimes
language level functionality provides greater flexibility or safety. In this
case use the language feature.
- If both offer equivalent functionality, don’t use
language feature. Why? Because most probably, the language level feature is
internally calling the object level functionality anyway.
Now there are three places where such additional functionality
is possibly available.
| Instance member |
Works on object instances only. mystring.length() example above.
|
| Shared member |
Works at class level, instance is not required. Refer to string.concat
example. |
| Related class member |
The functionality is elsewhere in some other class. That class is either
related or more generic to the current one. See the regex example below.
|
Consider the related class example now.
It is possible that the functionality you are looking for
is in some apparently unrelated class.
Here is the problem. We have a string “This is a repetitive
string”. I want to find out how many times does the word “is”
appear in it.
You would typically search in the properties and methods
of the string object. But you will not find anything there. Therefore, you have
to now look for more generic and related classes. Here is the actual code.
Dim mystring As String = “This is a repetitive string”
Dim re As New Regex(“is”)
MsgBox(System.Convert.ToInt32(re.Matches(mystring).Count))
Return
This will return the number 2 because the word ‘is’
appears twice. Now the regex class is available in a place called System.Text.RegularExpressions
class. Why was this functionality simply not given at string level? Because
it is a much larger and complex ballgame than just finding strings within another
string. As this functionality is not available at string level or as a language
level function, many of us will probably write long winding code to implement
this functionality. A proper search for the right place and the right DOT can
save us that trouble.
GoTo Definition
One of the most important things in finding the right place
it to use the Go To Definition functionality. Right-click on any object or class
and choose ‘Go To Definition’.
Here you can read more details about the exact functionality
available and read things in detail.
Importance of Class browser
Go To Definition also takes you to the class browser. But,
how do you find unrelated functionality hidden in some class far, far away?
The best place is Class Browser. This itself allows you to explode any class
hierarchy and look at the member properties, methods, fields and so on.
It shows the definition and short description about each
item. This is extremely well cross-referenced. This means you can cross navigate
in related objects to find the right place.
Examples
Here is an interesting case. How do you find the difference
between dates? That too in minutes, hours and so on. Of course the datediff
function still is available. But just out of curiosity if you try to find equivalent
DOT based functionality, here is what we get.
Dim strt As System.DateTime,
endt As System.DateTime
strt = “05-Jul-2004 18:11”
endt = “05-Jul-2004 20:23”
MsgBox(System.Convert.ToInt32(endt.Subtract(strt).TotalMinutes)
Now
let us understand this step by step.
- We defined two datetime objects and assigned values to
them.
- Now the datetime object itself has a subtract method. The
end-date subtract method accepts start-date time as the parameter.
- Now here is the fun. Instead of returning a value, it returns
another OBJECT called TimeSpan. This has its own properties and methods –
lots of them. One of them is TotalMinutes. This returns total minutes between
the two dates. But the datatype of the returned value is not ‘integer’,
as you might expect. It is ‘double’.
- Now we need to convert ‘double’ into ‘integer’.
Till now we were working on datetime and timespan classes. Now for converting
‘double’ to ‘integer’ these objects have no relevance.
Now we have to look at some other place.
- This is a conversion operation. So a quick search on ‘convert’
in Class Browser reveals a Convert class itself. This provides lots of conversion
types. One of which is called ToInt32. Various data types can be converted to
‘Int 32’ type. So for each it offers an overloaded shared method.
So now we can use system.convert.ToInt32( <double data type>) and then
we finally get the results.
- Of course using DateDiff is much simpler. But if you consider
the combined set of functionality offered by datetime, timespan and convert
classes, it is a phenomenal collection. We need to remember to use it in the
right place where an existing function may simply not be available or be adequate
enough for your purpose.
Using the concept in your application design
Observing and using the base functionality provided by the
powerful DOT is one thing. We also need to understand how to learn from it and
use these concepts effectively when you are designing your own application objects.
More on this later.
Acknowledgement
This article was written based on inputs and creative examples
suggested by Raj Chaudhuri, a close friend. In fact during a seminar we conducted
on .NET, we came up with the concept of the Power of the DOT. Soon we realised
that it is such a useful thought that it needs to be shared with the community.
|