Coding tests have been the standard way of measuring a software developer's programming ability in the IT industry. They can be challenging for both students and working professionals alike. Practically speaking, knowing what inbuilt functions are available or what are all the methods an Object exposes could help you come up with an approach a lot faster in a coding test. However, at the same time, one can’t remember all the methods or properties a class provides.
The Solution:
It’s quite simple; we need to find a way to get all the methods of an object or the inbuilt functions from the code itself. Yes!, We’re going to make our code help us solve the problem! (the irony!). I’ve found ways to do this for a few of the more popular programming languages, and I’ll be sharing them here with you.
Java:
Java provides a Method
class and a getMethods()
method which returns an array of all the public methods provided by a class. Make sure to replace the StringBuffer
class with your required class name!
import java.lang.reflect.Method;
public class HelloWorld {
public static void main(String args[]) {
Class<?> a = StringBuffer.class;
Method[] methods = a.getMethods();
for (Method methodName: methods)
System.out.println(methodName);
}
}
Python:
Python provides a magic method \_\_doc\_\_
which gets the documentation related to a module!.
import argparse
print(argparse.__doc__)
There is also the handy dir()
method which returns a list of all names in scope with the variable and the names without any underscores in them are the methods.
from pprint import pprint
pprint(dir(dict))
C#:
Like Java, C# also provides a method Type.GetMethods() which returns the information about all the public methods. However, a little more work is required to get the desired result.
using System;
using System.Linq;
public class HelloWorld
{
public static void Main()
{
//replace DateTime with your choice of class.
ShowMethods(typeof(DateTime));
}
//Prints method name with return type to console
static void ShowMethods(Type type)
{
foreach (var method in type.GetMethods())
{
var methodParameters = method.GetParameters();
var methodTypeNames = string.Join
(", ", methodParameters
.Select(x => x.ParameterType + " " + x.Name)
.ToArray());
Console.WriteLine("{0} {1} ({2})",
method.ReturnType,
method.Name,
methodTypeNames);
}
}
}
This article is still a work in progress, and I’ll be adding snippets of other languages soon. However, you get the idea right? You can share your tips or code snippets in the comment section below.
I wish you all the best for your next coding test!