I know there are a number of post out there on Interfaces and Base classes, but I'm having a hard time getting the correct design pattern understanding.
If I were to write a reporting class, my initial though would be to create an interface with the core properties, methods, etc. that all reports will implement.
For example:
Public Interface IReportSales
Property Sales() As List(Of Sales)
Property ItemTotalSales() As Decimal
End Interface
Public Interface IReportProducts
Property Productss() As List(Of Inventory)
Property ProductsTotal() As Decimal
End Interface
Then I assume I would have a class to implement the interface:
Public Class MyReport
Implements IReportSales
Public Property Sales() As System.Collections.Generic.List(Of Decimal) Implements IReportItem.Sales
Get
Return Sales
End Get
Set(ByVal value As System.Collections.Generic.List(Of Decimal))
Items = value
End Set
End Property
Public Function ItemTotalSales() As Decimal Implements IReport.ItemTotalSales
Dim total As Decimal = 0.0
For Each item In Me.Sales
total = total + item
Next
End Function
End Class
My thought was that it should be an interface because other reports may not use "Items", this way I can implement the objects that are used for a given report class.
Am I way off? should I have still have just created a base class? My logic behind not creating a base class was that not all report classes may use "Items" so I didn't want to define them where they are not being used.
To attempt to answer you question, abstract classes are used to provide a common ancestor for related classes. An example of this in the .Net API is TextWriter. This class provides a common ancestor all various classes whose purpose is to write text in some fashion.
Interfaces are more properly used to act as adapters for different objects that don't belong in the same "family" of objects but have similar capabilities. A good example of this can be seen with the various collections in the .Net API.
For example, the List and Dictionary classes provide the ability for you to manage a collection of objects. They do not share a common ancestor by inheritance, this wouldn't make sense. In order to allow easy interop between them though, they implement some of the same interfaces.
Both classes implement IEnumerable. This cleanly allows you use objects of either type List or Dictionary as an operand for anything that requires an IEnumerable. How wonderful!
So now in your case in designing new software you want to think about how this would fit into your problem space. If you give these classes a common ancestor via inheritance of an abstract class you have to be sure that all the items that inherit from it are truly of the base type. (A StreamWriter is a TextWriter, for example). Inappropriate use of class inheritance can make your API very difficult to build and modify in the future.
Let's say you make an abstract class, ReportBase, for your repots. It may contain a few very generic methods that all reports simply must have. Perhaps it simply specifies the method Run()
You then only have one type of report you want to make so you define a concrete Report class that inherits from ReportBase. Everything is great. Then you find out you need to add several more types of reports, XReport, YReport, and ZReport for sake of example. It doesn't really matter what they are, but they work differently and have different requirements. All of the reports generate pretty HTML output and everyone is happy.
Next week your client says they want XReport and YReport to be able to output PDF documents as well. Now there are many ways to solve this, but obviously adding an OutputPdf method to your abstract class is a poor idea, as some of those reports shouldn't or can't support this behavior!
Now this is where interfaces could be useful to you. Let's say you define a few interfaces IHtmlReport and IPdfReport. Now the report classes that are supposed to support these various output types can implement those interfaces. This will then let you create a function such as CreatePdfReports(IEnumerable<IPdfReport> reports) that can take all reports that implement IPdfReport and do whatever it needs to do with them without caring what the appropriate base type is.
Hopefully this helps, I was kind of shooting from the hip here as I'm not familiar with the problem you're trying to solve.
Yes, if you don't know how many reports are not going to use Items , you can go for Abastract class.
Another good thought follows:
You can also create both Interface and Abstract class
Define Sales in Interface , create two abstract classes , one for Reports that implement both and another for Report not implementing Sales. Implement interface for both
define both method (implement sales) in first and only implement sales in second.
Give appropriate names to both Abstract classes e.g. ReportWithItemsBase or ReportWithoutItemsBase.
This way you can also achieve self explaining named base classes on deriving Report classes as well.
I have a ASP.NET web application which has a UI project and BL project. The BL project handles all business logic and data access part.I call the BL methods from my UI by Simply calling the method on the instances.
Public Class User
Public Property UserID As Integer
Public Property FirstName As String
//rest of the properties for user
Public Sub Save()
//save the details to the database
End sub
End Class
and from my UI (its in C#) i do this.
User objUser=new User();
objUser.FirstName="Happy";
objUser.Save();
Everything works fine. Since the project is growing, i thought about trying to add some kind of unit testing/dependency injections tests. Googled around and saw every example uses Interfaces. I read so much about interfaces but don't know how to include interfaces in my coding and makes it to follow a better (scalable & testable) pattern. Other than testability, will it give me some other advantage ?
Can someone provide me a sample how to do that ?
Take a look at the Model-View-Controller design pattern and the asp.net mvc framework. There is a good overview here that explains the benefits of this design strategy.
An excerpt here:
The MVC pattern helps you create applications that separate the
different aspects of the application (input logic, business logic, and
UI logic), while providing a loose coupling between these elements.
The pattern specifies where each kind of logic should be located in
the application. The UI logic belongs in the view. Input logic belongs
in the controller. Business logic belongs in the model. This
separation helps you manage complexity when you build an application,
because it enables you to focus on one aspect of the implementation at
a time. For example, you can focus on the view without depending on
the business logic.
The loose coupling between the three main components of an MVC
application also promotes parallel development. For example, one
developer can work on the view, a second developer can work on the
controller logic, and a third developer can focus on the business
logic in the model.
Coding to interfaces gives plenty of advantages, better testability being one side-effect related to the main advantage: decoupling an object from its dependencies.
Say I have a class A, and in its implementation it uses class B. If you don't provide an interface to B, then you tightly coupled the design of A and B together (you cannot consider A without this specific implementation of B, as it uses the concrete implementation).
If you write an interface to B (say IB) and use it in A instead of using directly B, then you decoupled the design, and made them independent. A is now able to function independently of the specific inplementation B, it only knows an interface to it (IB) and the methods it needs to run on it. So if later on, you decide that your implementation of B wasn't good, or if you want to have A able to work on two different IB depending on the context, you can replace B with B2, which also implements IB, so you don't have to modify A at all.
The action to create A by injecting an implementation of IB at runtime like that:
A myA = new A(new B()); // this could also be new A(new B2()); or anythign else that implements IB
is called dependency injection, and is the best way to achieve a much desirable feature of OO programming: inversion of control (It's not A that control the behaviour of its dependencies anymore, it's an independent class - the factory - that controls what is injected into A).
For testability purpose, you can then unit-test A without making assumptions on B (which obviously needs to be tested separately). So in your tests, you can inject into A a stub or a mocked implementation of B, that will help you test the behaviour you want.
(Sorry no actual codes examples, as I'm a Java developer and not very good with the syntax of C#)
An interface is a description of functionality for a class. Any class that implements the interface must implement the interface's properties, methods, indexers, and/or events. An interface contains no implementation, only the signatures for the functionality the interface provides.
There are a few advantages to using interfaces. One of the big ones is that it allows you to get around the lack of multiple inheritance in .NET. You cannot inherit from multiple classes in .NET, but you can implement multiple interfaces.
Other benefits include loose coupling, easier maintainability, and makes code reuse more accessible since implementation is separated from the interface.
Here's a simple example of how your code could use an interface (using VB.NET):
Public Interface iPerson
Property FirstName As String
Property LastName As String
'Rest of properties for a person
Sub Save()
End Interface
Public Class User
Implements iPerson
Public Property UserId As Integer
Public Property FirstName As String Implements iPerson.FirstName
Public Property LastName As String Implements iPerson.LastName
Public Sub Save() Implements iPerson.Save
'Add code to save user
End Sub
End Class
And from your UI you could then do:
Dim objUser as iPerson = New User
objUser.FirstName = "Bob"
objUser.LastName = "Mckenzie"
ctype(objUser, User).UserId = 12345
If you then decided to create a new class implementing iPerson (ie - SuperUser) most of the code in your UI could remain the same:
Dim objUser as iPerson = New SuperUser
objUser.FirstName = "Bob"
objUser.LastName = "Mckenzie"
'The next line would throw a runtime error since object is not of type user
ctype(objUser, User).UserId = 12345
You could add a layer to bridge the UI and BL. I'm not a fan of the UI knowing anything about the BL. This can be accomplished with interfaces, but it doesn't need to be done with them.
I come from low level languages - C++ is the highest level I program in.
Recently I came across Reflection, and I just cannot fathom how it could be used without code smells.
The idea of inspecting a class/method/function during runtime, in my opinion, points to a flaw in design - I think most problems Reflection (tries to) solve could be used with either Polymorphism or proper use of inheritance.
Am I wrong? Do I misunderstand the concept and utility of Reflection?
I am looking for a good explanation of when to utilize Reflection where other solutions will fail or be too cumbersome to implement as well as when NOT to use it.
Please enlighten this low-level lubber.
Reflection is most commonly used to circumvent the static type system, however it also has some interesting use cases:
Let's write an ORM!
If you're familiar with NHibernate or most other ORMs, you write classes which map to tables in your database, something like this:
// used to hook into the ORMs innards
public class ActiveRecordBase
{
public void Save();
}
public class User : ActiveRecordBase
{
public int ID { get; set; }
public string UserName { get; set; }
// ...
}
How do you think the Save() method is written? Well, in most ORMs, the Save method doesn't know what fields are in derived classes, but it can access them using reflection.
Its wholly possible to have the same functionality in a type-safe manner, simply by requiring a user to override a method to copy fields into a datarow object, but that would result in lots of boilerplate code and bloat.
Stubs!
Rhino Mocks is a mocking framework. You pass an interface type into a method, and behind the scenes the framework will dynamically construct and instantiate a mock object implementing the interface.
Sure, a programmer could write the boilerplate code for the mock object by hand, but why would she want to if the framework will do it for her?
Metadata!
We can decorate methods with attributes (metadata), which can serve a variety of purposes:
[FilePermission(Context.AllAccess)] // writes things to a file
[Logging(LogMethod.None)] // logger doesn't log this method
[MethodAccessSecurity(Role="Admin")] // user must be in "Admin" group to invoke method
[Validation(ValidationType.NotNull, "reportName")] // throws exception if reportName is null
public void RunDailyReports(string reportName) { ... }
You need to reflect over the method to inspect the attributes. Most AOP frameworks for .NET use attributes for policy injection.
Sure, you can write the same sort of code inline, but this style is more declarative.
Let's make a dependency framework!
Many IoC containers require some degree of reflection to run properly. For example:
public class FileValidator
{
public FileValidator(ILogger logger) { ... }
}
// client code
var validator = IoC.Resolve<FileValidator>();
Our IoC container will instantiate a file validator and pass an appropriate implementation of ILogger into the constructor. Which implementation? That depends on how its implemented.
Let's say that I gave the name of the assembly and class in a configuration file. The language needs to read name of the class as a string and use reflection to instantiate it.
Unless we know the implementation at compile time, there is no type-safe way to instantiate a class based on its name.
Late Binding / Duck Typing
There are all kinds of reasons why you'd want to read the properties of an object at runtime. I'd pick logging as the simplest use case -- let say you were writing a logger which accepts any object and spits out all of its properties to a file.
public static void Log(string msg, object state) { ... }
You could override the Log method for all possible static types, or you could just use reflection to read the properties instead.
Some languages like OCaml and Scala support statically-checked duck-typing (called structural typing), but sometimes you just don't have compile-time knowledge of an objects interface.
Or as Java programmers know, sometimes the type system will get your way and require you to write all kinds of boilerplate code. There's a well-known article which describes how many design patterns are simplified with dynamic typing.
Occasionally circumventing the type system allows you to refactor your code down much further than is possible with static types, resulting in a little bit cleaner code (preferably hidden behind a programmer friendly API :) ). Many modern static languages are adopting the golden rule "static typing where possible, dynamic typing where necessary", allowing users to switch between static and dynamic code.
Projects such as hibernate (O/R mapping) and StructureMap (dependency injection) would be impossible without Reflection. How would one solve these with polymorphism alone?
What makes these problems so difficult to solve any other way is that the libraries don't directly know anything about your class hierarchy - they can't. And yet they need to know the structure of your classes in order to - for example - map an arbitrary row of data from a database to a property in your class using only the name of the field and the name of your property.
Reflection is particularly useful for mapping problems. The idea of convention over code is becoming more and more popular and you need some type of Reflection to do it.
In .NET 3.5+ you have an alternative, which is to use expression trees. These are strongly-typed, and many problems that were classically solved using Reflection have been re-implemented using lambdas and expression trees (see Fluent NHibernate, Ninject). But keep in mind that not every language supports these kinds of constructs; when they're not available, you're basically stuck with Reflection.
In a way (and I hope I'm not ruffling too many feathers with this), Reflection is very often used as a workaround/hack in Object-Oriented languages for features that come for free in Functional languages. As functional languages become more popular, and/or more OO languages start implementing more functional features (like C#), we will most likely start to see Reflection used less and less. But I suspect it will always still be around, for more conventional applications like plugins (as one of the other responders helpfully pointed out).
Actually, you are already using a reflective system everyday: your computer.
Sure, instead of classes, methods and objects, it has programs and files. Programs create and modify files just like methods create and modify objects. But then programs are files themselves, and some programs even inspect or create other programs!
So, why is it so OK for a Linux install to be reflexive that nobody even thinks about it, and scary for OO programs?
I've seen good usages with custom attributes. Such as a database framework.
[DatabaseColumn("UserID")]
[PrimaryKey]
public Int32 UserID { get; set; }
Reflection can then be used to get further information about these fields. I'm pretty sure LINQ To SQL does something similar...
Other examples include test frameworks...
[Test]
public void TestSomething()
{
Assert.AreEqual(5, 10);
}
Without reflection you often have to repeat yourself a lot.
Consider these scenarios:
Run a set of methods e.g. the testXXX() methods in a test case
Generate a list of properties in a gui builder
Make your classes scriptable
Implement a serialization scheme
You can't typically do these things in C/C++ without repeating the whole list of affected methods and properties somewhere else in the code.
In fact C/C++ programmers often use an Interface description language to expose interfaces at runtime (providing a form of reflection).
Judicious use of reflection and annotations combined with well defined coding conventions can avoids rampant code repetition and increase maintainability.
I think that reflection is one of these mechanisms that are powerful but can be easily abused. You're given the tools to become a "power user" for very specific purposes, but it is not meant to replace proper object oriented design (just as object oriented design is not a solution for everything) or to be used lightly.
Because of the way Java is structured, you are already paying the price of representing your class hierarchy in memory at runtime (compare to C++ where you don't pay any costs unless you use things like virtual methods). There is therefore no cost rationale for blocking it fully.
Reflection is useful for things like serialization - things like Hibernate or digester can use it to determine how to best store objects automatically. Similarly, the JavaBeans model is based on names of methods (a questionable decision, I admit), but you need to be able to inspect what properties are available to build things like visual editors. In more recent versions of Java, reflections is what makes annotations useful - you can write tools and do metaprogramming using these entities that exist in the source code but can be accessible at runtime.
It is possible to go through an entire career as a Java programmer and never have to use reflection because the problems that you deal with don't require it. On the other hand, for certain problems, it is quite necessary.
As mentioned above, reflection is mostly used to implement code that needs to deal with arbitrary objects. ORM mappers, for instance, need to instantiate objects from user-defined classes and fill them with values from database rows. The simplest way to achieve this is through reflection.
Actually, you are partially right, reflection is often a code smell. Most of the time you work with your classes and do not need reflection- if you know your types, you are probably sacrificing type safety, performance, readability and everything that's good in this world, needlessly. However, if you are writing libraries, frameworks or generic utilities, you will probably run into situations best handled with reflection.
This is in Java, which is what I'm familiar with. Other languages offer stuff that can be used to achieve the same goals, but in Java, reflection has clear applications for which it's the best (and sometimes, only) solution.
Unit testing software and frameworks like NUnit use reflection to get a list of tests to execute and executes them. They find all the test suites in a module/assembly/binary (in C# these are represented by classes) and all the tests in those suites (in C# these are methods in a class). NUnit also allows you to mark a test with an expected exception in case you're testing for exception contracts.
Without reflection, you'd need to specify somehow what test suites are available and what tests are available in each suite. Also, things like exceptions would need to be tested manually. C++ unit testing frameworks I've seen have used macros to do this, but some things are still manual and this design is restrictive.
Paul Graham has a great essay that may say it best:
Programs that write programs? When
would you ever want to do that? Not
very often, if you think in Cobol. All
the time, if you think in Lisp. It
would be convenient here if I could
give an example of a powerful macro,
and say there! how about that? But if
I did, it would just look like
gibberish to someone who didn't know
Lisp; there isn't room here to explain
everything you'd need to know to
understand what it meant. In Ansi
Common Lisp I tried to move things
along as fast as I could, and even so
I didn't get to macros until page 160.
concluding with . . .
During the years we worked on Viaweb I
read a lot of job descriptions. A new
competitor seemed to emerge out of the
woodwork every month or so. The first
thing I would do, after checking to
see if they had a live online demo,
was look at their job listings. After
a couple years of this I could tell
which companies to worry about and
which not to. The more of an IT flavor
the job descriptions had, the less
dangerous the company was. The safest
kind were the ones that wanted Oracle
experience. You never had to worry
about those. You were also safe if
they said they wanted C++ or Java
developers. If they wanted Perl or
Python programmers, that would be a
bit frightening-- that's starting to
sound like a company where the
technical side, at least, is run by
real hackers. If I had ever seen a job
posting looking for Lisp hackers, I
would have been really worried.
It is all about rapid development.
var myObject = // Something with quite a few properties.
var props = new Dictionary<string, object>();
foreach (var prop in myObject.GetType().GetProperties())
{
props.Add(prop.Name, prop.GetValue(myObject, null);
}
Plugins are a great example.
Tools are another example - inspector tools, build tools, etc.
I will give an example of a c# solution i was given when i started learning.
It contained classes marked with the [Exercise] attribute, each class contained methods which were not implemented (throwing NotImplementedException). The solution also had unit tests which all failed.
The goal was to implement all the methods and pass all the unit tests.
The solution also had a user interface which it would read all class marked with Excercise, and use reflection to generate a user interface.
We were later asked to implement our own methods, and later still to understand how the user interface 'magically' was changed to include all the new methods we implemented.
Extremely useful, but often not well understood.
The idea behind this was to be able to query any GUI objects properties, to provide them in a GUI to get customized and preconfigured. Now it's uses have been extended and proved to be feasible.
EDIT: spelling
It's very useful for dependency injection. You can explore loaded assemblies types implementing a given interface with a given attribute. Combined with proper configuration files, it proves to be a very powerful and clean way of adding new inherited classes without modifying the client code.
Also, if you are doing an editor that doesn't really care about the underlying model but rather on how the objects are structured directly, ala System.Forms.PropertyGrid)
Without reflection no plugin architecture will work!
Very simple example in Python. Suppose you have a class that have 3 methods:
class SomeClass(object):
def methodA(self):
# some code
def methodB(self):
# some code
def methodC(self):
# some code
Now, in some other class you want to decorate those methods with some additional behaviour (i.e. you want that class to mimic SomeClass, but with an additional functionality).
This is as simple as:
class SomeOtherClass(object):
def __getattr__(self, attr_name):
# do something nice and then call method that caller requested
getattr(self.someclass_instance, attr_name)()
With reflection, you can write a small amount of domain independent code that doesn't need to change often versus writing a lot more domain dependent code that needs to change more frequently (such as when properties are added/removed). With established conventions in your project, you can perform common functions based on the presence of certain properties, attributes, etc. Data transformation of objects between different domains is one example where reflection really comes in handy.
Or a more simple example within a domain, where you want to transform data from the database to data objects without needing to modify the transformation code when properties change, so long as conventions are maintained (in this case matching property names and a specific attribute):
///--------------------------------------------------------------------------------
/// <summary>Transform data from the input data reader into the output object. Each
/// element to be transformed must have the DataElement attribute associated with
/// it.</summary>
///
/// <param name="inputReader">The database reader with the input data.</param>
/// <param name="outputObject">The output object to be populated with the input data.</param>
/// <param name="filterElements">Data elements to filter out of the transformation.</param>
///--------------------------------------------------------------------------------
public static void TransformDataFromDbReader(DbDataReader inputReader, IDataObject outputObject, NameObjectCollection filterElements)
{
try
{
// add all public properties with the DataElement attribute to the output object
foreach (PropertyInfo loopInfo in outputObject.GetType().GetProperties())
{
foreach (object loopAttribute in loopInfo.GetCustomAttributes(true))
{
if (loopAttribute is DataElementAttribute)
{
// get name of property to transform
string transformName = DataHelper.GetString(((DataElementAttribute)loopAttribute).ElementName).Trim().ToLower();
if (transformName == String.Empty)
{
transformName = loopInfo.Name.Trim().ToLower();
}
// do transform if not in filter field list
if (filterElements == null || DataHelper.GetString(filterElements[transformName]) == String.Empty)
{
for (int i = 0; i < inputReader.FieldCount; i++)
{
if (inputReader.GetName(i).Trim().ToLower() == transformName)
{
// set value, based on system type
loopInfo.SetValue(outputObject, DataHelper.GetValueFromSystemType(inputReader[i], loopInfo.PropertyType.UnderlyingSystemType.FullName, false), null);
}
}
}
}
}
}
// add all fields with the DataElement attribute to the output object
foreach (FieldInfo loopInfo in outputObject.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance))
{
foreach (object loopAttribute in loopInfo.GetCustomAttributes(true))
{
if (loopAttribute is DataElementAttribute)
{
// get name of field to transform
string transformName = DataHelper.GetString(((DataElementAttribute)loopAttribute).ElementName).Trim().ToLower();
if (transformName == String.Empty)
{
transformName = loopInfo.Name.Trim().ToLower();
}
// do transform if not in filter field list
if (filterElements == null || DataHelper.GetString(filterElements[transformName]) == String.Empty)
{
for (int i = 0; i < inputReader.FieldCount; i++)
{
if (inputReader.GetName(i).Trim().ToLower() == transformName)
{
// set value, based on system type
loopInfo.SetValue(outputObject, DataHelper.GetValueFromSystemType(inputReader[i], loopInfo.FieldType.UnderlyingSystemType.FullName, false));
}
}
}
}
}
}
}
catch (Exception ex)
{
bool reThrow = ExceptionHandler.HandleException(ex);
if (reThrow) throw;
}
}
One usage not yet mentioned: while reflection is generally thought of as "slow", it's possible to use Reflection to improve the efficiency of code which uses interfaces like IEquatable<T> when they exist, and uses other means of checking equality when they do not. In the absence of reflection, code that wanted to test whether two objects were equal would have to either use Object.Equals(Object) or else check at run-time whether an object implemented IEquatable<T> and, if so, cast the object to that interface. In either case, if the type of thing being compared was a value type, at least one boxing operation would be required. Using Reflection makes it possible to have a class EqualityComparer<T> automatically construct a type-specific implementation of IEqualityComparer<T> for any particular type T, with that implementation using IEquatable<T> if it is defined, or using Object.Equals(Object) if it is not. The first time one uses EqualityComparer<T>.Default for any particular type T, the system will have to go through more work than would be required to test, once, whether a particular type implements IEquatable<T>. On the other hand, once that work is done, no more run-time type checking will be required since the system will have produced a custom-built implementation of EqualityComparer<T> for the type in question.