Newbie Qn - Interfaces as parameters and members

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi all

I want to know if I can have interfaces as formal parameters in methods.

For instance, if I have something like this

public interface INameTranslator
{
string sToLocal(string sRemoteName);
string sToRemote(string sLocalName);
}

Can I do this..

public class CMyNameTranslator: INameTranslator
{
public string sToLocal(string sRemoteName)
{
return sRemoteName;
}
public string sToRemote(string sLocalName)
{
return sLocalName;
}
}

public class CFoo
{
public INameTranslator mNameTranslator;
CFoo(INameTranslator NameTranslator) //<<--- Is this legal /desirable
{
mNameTranslator = NameTranslator;
}
}

AND then somewhere else..

CMyNameTranslator NameTranslator = new CMyNameTranslator();
CFoo Foo = new CFoo(NameTranslator);
string sTemp = Foo.mNameTranslator.sToLocal("Bob"); // sTemp should be
"Bob"

Cheers

Steve
 
Hi Steve,
no reason why you cannot do this. The idea of having an interface is that
you can abstract away in your code from having to worry about the actual
concrete class that implements the interface, you don't care what type the
object is in your functions as long as it implements your interface.

Mark.
 
I wouldn't expose your class member variables as public, let other classes
access them through properties.

You want to hide what is going on inside your class from the outside world,
what if you want to change the name of the internal variable, it's type, how
it is stored, if you have exposed the variable directly then other classes
will need to be changed to.

When you write your classes you want them to be:
1. Highly Cohesive - meaning that all of the functionality inside the class
is pertinent to one piece of functionality.
2. Loosely Coupled - meaning that there is a well defined interface between
different object and they only are connected through this. You do not want
different classes to be tightly linked to eachothers inner workings otherwise
it is difficult to refactor and can introduce errors in one class when
another is modified.


Hope that helps
Mark.
 
Thanks for that Mark.

I thought it was probably ok.. at least the compiler didn't complain
 
Back
Top