How do I refer to two different classes by one name in vb.net - vb.net

I have two classes to handle database operations, one for MySQL (DBMySQL), and another for SQLite (DBSQLite). The user chooses which database system to use.
The functions within the classes have the same names, but are obviously slightly different to handle the variations in databases.
I would like to refer to the chosen class by one name throughout the application. I have set a global variable DB.
In a procedure I can: Dim DB as New DBMySQL (or DBSQLite). This works within the procedure, but not globally, but I can see all the functions when coding.
If I instead use: DB = New DBMySQL, this works globally, but no class functions are displayed when coding.
Any alternatives?

Use the concept of inheritance, and create a MustInherit class with MustOverride methods and/or properties.
Public MustInherit Class AbstractDB
Public MustOverride Function MyQuery(input As Object) As Object
Public MustOverride Sub MyUpdateMethod(input As Object)
End Class
Public Class DBMySQL
Inherits AbstractDB
Public Overrides Function MyQuery(input As Object) As Object
End Function
Public Overrides Sub MyUpdateMethod(input As Object)
End Sub
End Class
Public Class DBSQLite
Inherits AbstractDB
Public Overrides Function MyQuery(input As Object) As Object
End Function
Public Overrides Sub MyUpdateMethod(input As Object)
End Sub
End Class
Then, when you want to use your classes, make your DB global variable of type AbstractDB. You could then create either DBMySql or DBSQLite and assign it to your DB variable. The method names will all be the same, because they all inherit the same base class. But each derived class must fill out the content of those methods on its own.
Dim DB as AbstractDB = New DBMySQL

You could also use an interface.
Public Interface IRepository
' common functions of MySQL and SQLLiteclasses
End Interface
Public Class MySQLRepository
Implements IRepository
End Class
Public Class SQLLiteRepository
Implements IRepository
End Class
Public Function GetDB(userChoice As String) As IRepository
If userChoice = "MySQL" Then
Return New MySQLRepository()
Else
Return New SQLLiteRepository
End if
End Function
Dim DB As IRepository = GetDB(userChoice)
This is a basic implementation of the Repository pattern. The example in the link is in C#, but, as you're probably aware, it's not easy finding examples in VB. Fortunately, there are lots of C# to VB converters.
The abstract example Sean Skelly gave should also work. You may want to research the difference between abstract classes and interfaces.

Related

Named Constructor Idiom in VB.NET?

Is using the Named Constructor Idiom possible in VB.NET? I've found many examples in C#/C++ but can't quite wrap my head around how to use it in vb.net. Seems like a better method of keeping my code readable when involving a lot of constructors with similar argument types.
I've never heard this term before, but after a quick search it sounds vaguely like the Static Factory Pattern. The idea is you make the constructor private and use a shared (static in c#) public function to create the new object.
Public Class Foo
Private Sub New()
End Sub
Public Shared Function CreateNew(param as Object) as Foo
Dim obj as New Foo()
obj.Prop = param
return obj
End Function
End Class
You sure can make Named Constructors in VB. The pattern uses a static (Shared in VB) factory method on the class itself, so that the method can be named. (Other Factory patterns involve using a separate Factory class to provide the static method.)
System.Drawing.Color is a simple example. The pattern is implemented underneath as a static (Shared) property. Since no arguments are necessary, the Get method of a Property works just fine:
Public Shared ReadOnly Property Chartreuse As Color
Usage:
Dim favoriteColor as Color = Color.Chartreuse
Or you can make static factory methods to do the same thing.
Public Class TheClass
Public Sub New()
End Sub
Public Sub New(input As String)
'do something with input
End Sub
Public Shared Function MyNamedConstructor() As TheClass
Return New TheClass
End Function
Public Shared Function AnotherNamedConstructor() As TheClass
Return New TheClass("Another Name")
End Function
End Class
As for whether this pattern is "better" than overloading constructors, that's really an opinion. Personally, I would just overload the constructors. As you can see in the example above, the constructors need to be there anyway.
I suggest using the Named Constructor pattern when you have only a few possible ways to construct your class/struct, but consumers of your class/struct will be using those few constructors often, and with different input values to those constructors (as in the System.Drawing.Color example).
The Name in 'Named Constructor' doesn't represent a name for the constructor itself, but for the object resulting from the constructor. If your named constructor can be used to create two objects that don't feel right to give the same name to, then don't give the constructor that name.

Generic Collection of T for ICollection of DbEntities

The Situation-
Have EF database entities with collections of other database entities as navigation properties all of which are not exposed outside of the project. Each of these entities are nested in base classes that allow public read and protected set access to the Db entity's property values and are the classes the business layer will work with. So these base classes also need collections of their Db entity's navigation properties.
What I have now-
I am still working on how I want the data layer to interact with with the other layers that reference it. So I have been experimenting with creating collection classes that can be set equal to a collection of Db entities and create a collection of the base class that the Db entity is nested in. The collection is then exposed outside the class though an interface as well as the base class. The interface gives access to some custom methods of collection class like accepting DTOs and prebuilt quires but would hide any Add methods.
The Problem-
I would like to create a generic base class for the collections but cant seem to find a way. I have gotten close to something workable but it was ugly and confusing. Below is an outline of what I'm working with. The narrowing operators in the entity class work well. I would rather have widening operators and narrowing operators in the base class so I could keep the New method private for the base classes but I don't want to expose the actual database entities outside the Data Layer.
Interops Namespace referenced by all projects in solution-
Public Interface IGenericEntity
End Interface
Public Interface INavigationPropertyEntity : Inherits IGenericEntity
End Interface
Public Interface IDbEntityToExposedEntityCollection(Of TEntity As IGenericEntity)
'Used to hide Add method
End Interface
Public Interface IPublicEntity
ReadOnly Property NavProps As IDbEntityToExposedEntityCollection(Of INavigationPropertyEntity)
End Interface
Data Layer project-
-Database Entities
Friend Class DbEntity1
Public Shared Narrowing Operator CType(ByVal value As DbEntity1) As NavigationPropertyEntity
Return New NavigationPropertyEntity(value)
End Operator
End Class
Friend Class DbEntity2
Public Sub New()
NavigationPropertyDbEntities = New HashSet(Of DbEntity1)
End Sub
Public Property NavigationPropertyDbEntities As ICollection(Of DbEntity1)
Public Shared Narrowing Operator CType(ByVal value As DbEntity2) As PublicEntity
Return New PublicEntity(value)
End Operator
End Class
-Exposed Base Classes
Public Class NavigationPropertyEntity : Implements INavigationPropertyEntity
Private _value As DbEntity1
Friend Sub New(value As DbEntity1)
_value = value
End Sub
End Class
Public Class PublicEntity : Implements IPublicEntity
Dim _value As DbEntity2
Friend _NavProps As DbEntityToPublicEntityCollection(Of INavigationPropertyEntity, DbEntity1, NavigationPropertyEntity)
Public ReadOnly Property NavProps As IDbEntityToExposedEntityCollection(Of INavigationPropertyEntity) Implements IPublicEntity.NavProps
Get
Return _NavProps
End Get
End Property
Friend Sub New(value As DbEntity2)
_value = value
_NavProps = new DbEntityToPublicEntityCollection(Of INavigationPropertyEntity, DbEntity1, NavigationPropertyEntity)(_value.NavigationPropertyDbEntities)
End Sub
End Class
-Entity Specific Collection
Friend Class DbEntityToPublicEntityCollection(Of IEnt As INavigationPropertyEntity, DbEnt As DbEntity1, ExpEnt As NavigationPropertyEntity)
Inherits HashSet(Of IEnt)
Implements IDbEntityToExposedEntityCollection(Of IEnt)
Public Sub New(value As HashSet(Of DbEnt))
For Each ent In value
Dim exp As NavigationPropertyEntity = ent
Dim i As INavigationPropertyEntity = exp
MyBase.Add(i)
Next
End Sub
End Class
Additional Info Edit
The main issue is being able to have a generic collection declared something like,
Friend Class DbEntityToPublicEntityCollection(Of IEnt, DbEnt as class, ExpEnt As class)
because in the New sub ExpEnt cannot be converted to DbEnt and a TryCast will just result in a runtime error.
Like I said, I tried setting up classes that are inherited by the exposed and entity classes so a new method with a parameter for the exposed class could be set up but with trying to have the interfaces in there it got unmanageable pretty quick. Then again I have not worked much with making my own generic types before so I'm not sure if this is even a proper strategy.

Enumeration vs Interface for constants

Is it a good design practice to change an enumeration type:
Public Enum EnumerationType
EnumerationMember1
EnumerationMember2
End Enum
To an interface base with implementor classes (even if they are empty)?
Public Interface IEnumerationType
End Interface
Public Class EnumerationMember1 : Implements IEnumerationType
End Class
Public Class EnumerationMember2 : Implements IEnumerationType
End Class
For extensibility purposes.
Is there any downside? Is there any case in which is preferable to use just an enum?
INTERFACES used for contracts between classes
that is when you have two non-related classes sharing some methods
Enumeration type stores special values. These are named constants. With an Enum, we replace magic constants throughout a program.
This improves code clarity,
organizes code
and makes code easier to maintain
For extensibility purposes it is better to use interface cause you will have methods properties and you can inherit the class later
Public Enum
with interface you have enumeration with advanced options so what the downsides will be ? No downside :)
It's not entire clear what you're after, but take a look at the strongly typed enum pattern.
''' <completionlist cref="EnumerationType"/>
Class EnumerationType
Private Key As String
Public Shared ReadOnly Member1 As EnumerationMember1 = New EnumerationMember1("EnumerationMember1")
Public Shared ReadOnly Member2 As EnumerationMember2 = New EnumerationMember2("EnumerationMember2")
Private Sub New(key as String)
Me.Key = key
End Sub
Public Overrides Function ToString() As String
Return Me.Key
End Function
End Class
So when you use it, it looks like an enum:
Sub Main
DoSomething(EnumerationType.EnumerationMember1)
DoSomething(EnumerationType.EnumerationMember2)
End Sub
Sub DoSomething(test As IEnumerationType)
Console.WriteLine(test.ToString())
End Sub
but you can easily add functionality to it (like explicit conversions, or a way to iterate over all members using a shared dictionary, or whatever comes to your mind).
It's typesafe, and using the magic completionlist comment will enable Intellisense support.

Can I have a function with return type of the class itself in inherited classes? VB.NET

I have a parent class that is also a factory. For example:
Public Class Factory
Public Function clone() as Factory
' Some logic here
' return something
End Function
Public Function all() as List (Of Factory)
' Some logic here
' return something
End Function
End Class
And then an inherited one
Public Class BookFactory
inherits Factory
End Class
I can use inflection in the Factory class to generate the proper extended objects when called by the inherited one. myBookFactory.clone() will then return a BookFactory instance and not only a Factory instance.
The problem: this BookFactory instance will be cast as Factory, since the type of the function is Factory and not BookFactory.
I'd like to do something like
Public Class Factory
Public Function clone() as Me.GetType()
' Some logic here
' return something
End Function
Public Function all() as List (Of Me.GetType())
' Some logic here
' return something
End Function
End Class
So the returned value would be correctly cast and avoid having to do this each time:
Dim myBookFactory2 = DirectCast(myBookFactory1.clone(), myBookFactory1.getType())
How can I do this?
This seems to be a variation on asking for covariant return types. As you have noticed, this is not supported by VB.NET (or C# for that matter). Typically this is asked in the context of overriding virtual methods, where it is still not allowed. There are several alternatives, each with their own pros and cons.
Use a generic template argument to specify the derived class
This is similar to the way IComparable<T> is most commonly implemented.
Public Class Factory(Of T As Factory)
Public Function Clone() As T
'use GetType(T) to determine derived type
End Function
End Class
Public Class BookFactory
Inherits Factory(Of BookFactory)
End Class
Additionally, if you can add a New constraint to the Factory (eg: Factory(Of T {New, Factory(Of T)})) base class, you may be able to avoid using reflection.
However, this does not prevent the accidental (or potentially malicious) mistake of declaring a class like this:
Public Class EvilFactory
Inherits Factory(Of BookFactory)
'hmmm, now clone will be making the wrong type
End Class
Also, this approach makes it impossible to create a list of factories of different types without resorting to another base class below Factory(Of T) or declaring the list as being of object.
Make new methods on the derived classes that return the specific type you want.
Public Class Factory
Public Function Clone() As Factory
'create derived class, but return as base
End Function
End Class
Public Class BookFactory
Inherits Factory
Public Function CloneBooks() As BookFactory
Return CType(Me.Clone(), BookFactory)
End Function
End Class
This allows you to hide the cast for those times when you know you have a BookFactory and want to get another BookFactory. It also lets you treat all factory types polymorphically in the normal inheritance sense. However, if you have an object typed as Factory, you will still get back an object type as Factory.
Reconsider the inheritance relationship
Depending on how these classes are used, it may not make sense to use the inheritance relationship here. If you are only concerned with not retyping code, you may want to look into code generation instead.
You could potentially use generics to make the problem easier, but it won't remove the requirement to cast at some point. For example:
Public Class Factory(Of T)
Public Function clone() As Factory(Of T)
' Some logic here
' return something
End Function
Public Function all() As Collections.Generic.List(Of T)
' Some logic here
' return something
End Function
End Class
Public Class BookFactory
Inherits Factory(Of Book)
End Class

VB.NET inheritance - do all properties in the derived classes have to be declared in the base class?

I'm refactoring, and have run into a roadblock.
Background:
I have a base class and several inherited derived classes. The derived classes don't always need to have the same properties. If any properties are shared among the derived classes, those properties would live at the base class level ('Contents', for example).
Similarly, GoodDocument below has 'GoodThings' but would not want/need to have 'BadThings'.
I want to treat instances of both 'GoodDocument' and 'BadDocument' as type 'Document'
public mustinherit class Document
public property Contents as string
public sub new()...
end class
public class GoodDocument
inherits Document
public property GoodThings as string
public sub new()...
end class
public class BadDocument
inherits Document
public property BadThings as string
public sub new()...
end class
The 'DocumentWriter' class will also have several derived classes: ('GoodDocumentWriter' and 'BadDocumentWriter').
I need to pass around the DocumentWriter.Doc as a 'Document' to a number of other places in the code. Doc.GoodThings would only be called from within an instance of either 'GoodDocument' or 'GoodDocumentWriter'.
public mustinherit class DocumentWriter
public property Doc as Document
public sub new()...
end class
public class GoodDocumentWriter
inherits DocumentWriter
public sub new
mybase.Doc = new GoodDocument
end sub
end class
public class BadDocumentWriter
inherits DocumentWriter
public sub new
mybase.Doc = new BadDocument
end sub
end class
Question:
Is there a design pattern that allows for derived classes to have members that don't exist at the base class level?
Do all properties have to live at the base class level?
Revised
I was trying to be brief with my initial question and I made the mistake of over simplifying the situation. In short, I did realize that it should be possible to have different properties on each of the derived classes. (I typed that in a tongue-in-cheek manor and didn't mean to keep it in the final post).
I realize now that the problem that I was experiencing was really symptomatic of a larger issue which needed addressing.
It appears that I was encountering compiler complaints that could be corrected by further refactoring and looser coupling. While others answered the basic question that I posed, Ryan Gross' example really helped kick start some new ideas.
Thanks!
What you should do in this case is define the operations that can be performed on instances of Document in an interface. In your case maybe there is a WriteThings operation, so you would have:
public interface Writeable {
public sub WriteThings();
}
Then in your derived classes you would implement the method to utilize the internal data of the class. For example:
public mustinherit class Document implements Writeable
public property Contents as string
public sub new()...
public sub WriteThings();
end class
public class GoodDocument
inherits Document
public property GoodThings as string
public sub new()...
public sub WriteThings()
//Do something with GoodThings
end sub
end class
public class BadDocument
inherits Document
public property BadThings as string
public sub WriteThings()
//Do something with BadThings
end sub
public sub new()...
end class
Finally, client code that needs to call WriteThings accesses it through an interface:
public mustinherit class DocumentWriter
public property Doc as Writable
public sub new()...
public sub PerformWrite()
Doc.WriteThings();
end sub
end class
It is generally not a good idea to build several parallel class hierarchies. In this case, one DocumentWriter class should be able to write any class that implements Writeable by invoking its WriteThings method.
If all the properties live at the base class level, then I'm not sure what the point of a derived class would be. :) You'd be able to do everything with the base class.
So, yes. If something is applicable only to GoodDocument and not to Document, then it should be in GoodDocument.
To answer your question specifically:
Yes, you just create multiple layers in the inheritance hierarchy: You have a base class, and then many two “branches” (good and bad, to use your terminology). Any properties that are only relevant to either branch, you declare in the class that inherits from the base class. Those properties will only be visible to that class and any classes inheriting from it.
No, properties can be declared anywhere within your inheritance hierarchy.