Can you make anonymous classes in vb.net? - vb.net

I'd like to do this in vb.net (c++ code)
struct Banana {
struct {
int width;
int height;
} Physical;
std::string name;
};
It basically serves to categorize the fields so I can go Banana.Physical.width. Now, I know I could technically do it like this
Public Class Banana
Public name As String
Public Physical As New PhysicalClass
Public Class PhysicalClass
Public width As Integer
Public height As Integer
End Class
End Class
But I was hoping maybe there is some syntax candy around so I wouldn't have to name the PhysicalClass that I would never use anywhere else anyways.

Related

How does the dot notation changes the internal representation for an object?

I am new to Object Oriented Programming. I have come across the concepts of Getters and Setters as well as Dot notation to manipulate the value of an object. It is suggested to use more of Getters and Setters methods instead of Dot notation method.
I tried to understand the reason behind this and found out that using the dot notation might change the internal representation of the object. But, the resource I referred did not tell how exactly this change happens.
Can someone please tell how this change actually looks like?
Thanks in advance!
Using getters and setters (or properties in some languages) is common practice because they promote encapsulation, one of the four principles of object oriented programming. The idea is that an object should have control over its own properties or members, and that outside classes should not be able to directly manipulate its properties or members.
You asked specifically about the internal representation of an object. Java, for instance, passes its members by value when you call a get function, but you are accessing the member directly with dot notation. For example take the following class:
public class Person {
public String name = "John";
public String getName() {
return name;
}
}
In this circumstance you could access the name member of the Person class through the getName() method, or you could access it through dot notation. If you use the getName() method then you can't inadvertently change the value of the name member. For example:
public static void main(String[] args) {
Person person = new Person();
String name = person.getName();
name = "Gary";
Sysetm.out.println(person.getName());
}
Will produce the output John, whereas the following:
public static void main(String[] args) {
Person person = new Person();
person.name = "Gary";
Sysetm.out.println(person.getName());
}
Will produce the output Gary.
The accepted practice for handling this person class is to use encapsulation, and set a private access modifier for its member, like so:
public class Person {
private String name = "John";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Now you can explicitly set the name member to whatever you would like using the setName method, but you will never be able to inadvertently change the name member by using dot notation.
Furthermore, there will often be times when you will want to do something with the member before it is returned or before it is set. A simple example would be the following:
public class Person {
private String name = "John";
public String getName() {
return name;
}
public void setName(String name) {
// null values are not allowed, and a name must be at least two characters long
if (name == null || name.length() < 2) {
return;
}
// name must be capitalzed
name = name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase();
this.name = name;
}
}
In summation, we do it this way because encapsulation makes code cleaner, more predictable, and more maintainable. I hope this helps!

Point to the function created in C# project from generic typename in C++/CLI

C++/CLI :
public interface class ITest{
public:
virtual void doSomething (){
}
}
public ref Base {
...........
...........
}
generic <typename T> where T : ITest
public ref Derived : Base{
public:
virtual void doNothing (){
}
}
public ref AnotherClass {
public:
generic<class T> where T : Base
static int justDoThis(){
//Problem!!
}
}
C# :
In C# there are two classes A and B. A inherits from the ITest and B inherits from Derived where A is used as the typename. Also, B has a private variable of type A. So, from main function AnotherClass.justDoThis<B>() is called where B is passed as the generic type.
"//Problem!!" Part :
Now I have to create a new instance of B in this section and also access the A which is private variable in B.
So if I take your paragraph of description of the C# code:
class A : ITest {}
class B : Derived<A>
{
private A someVariableOfTypeA;
}
class Program
{
void Main(string[] args)
{
AnotherClass.justDoThis<B>();
}
}
And the problem is that you want to do this:
public ref AnotherClass {
public:
generic<class T> where T : Base
static int justDoThis()
{
// Problem!!
Something^ actuallyB = gcnew Something();
A^ a = actuallyB->someVariableOfTypeA;
}
}
Issue #1: You can allow creation of new objects of the generic type by specifying gcnew as another generic constraint. (In C#, this would be new.) This will require that the generic type have a default (i.e., parameterless) constructor, which you can access with the normal gcnew.
generic<class T> where T : Base, gcnew
static int justDoThis()
{
T^ t = gcnew T();
}
Issue #2: You cannot access private variables within an object. That's what private means. If you want to give justDoThis access to the A object, then add an appropriate public method or property to Base. The method or property would return type ITest. You could also put that method/property on a new interface (perhaps named IHaveAnITestAccessorMethod), and add that as another generic constraint, and B satisfies all the constraints.
Note that it won't do any good to make the variable public on type B: justDoThis doesn't know about B, it only knows about T, which is a Base with a no parameter constructor.
Disclaimers:
I didn't check my syntax with a compiler.
Yes, you can do anything with reflection, but that's a bad design. Don't do that, fix your code the right way.

Interface Segregation Principle- Program to an interface

I was reading about SOLID and other design principles. I thought ISP was the same as "Program to an interface, not an implementation". But it looks like these are different principles?
Is there a difference?
Robert Martin has a very good explanation of Interface segregation principle (ISP), in his book "UML for Java Programmers". Based on that, I don't think ISP is about an interface being "focused" on one logical, coherent group of things. Because, that goes without saying; or, at least it should go without saying. Each class, interface or abstract class should be designed that way.
So, what is ISP? Let me explain it with an example. Say, you have a class A and a class B, which is the client of class A. Suppose, class A has ten methods, of which only two are used by B. Now, does B need to know about all ten methods of A? Probably not - the principle of Information hiding. The more you expose, the more you create the chance for coupling. For that reason, you may insert an interface, call it C, between the two classes (segregation). That interface will only declare the two methods that are used by B, and B will depend on that Interface, instead of directly on A.
So now,
class A {
method1()
method2()
// more methods
method10()
}
class B {
A a = new A()
}
will become
interface C {
method1()
method2()
}
class A implements C{
method1()
method2()
// more methods
method10()
}
class B {
C c = new A()
}
This, prevents B from knowing more than it should.
ISP is focused on the idea of each interface representing one discrete and cohesive behavior.
That is, each logical group of things an object should do would map to a single specific interface. A class might want to do several things, but each thing would map to a specific interface representing that behavior. The idea is each interface is very focused.
Assume that you have one fat interface with many methods to be implemented.
Any class, that implements that fat interface has to provide implementation for all these methods. Some of the methods may not be applicable to that concrete class. But still it has to provide implementation in absence of interface segregation principle.
Let's have a look at example code in absence of Interface segregation.
interface Shape{
public int getLength();
public int getWidth();
public int getRadius();
public double getArea();
}
class Rectangle implements Shape{
int length;
int width;
public Rectangle(int length, int width){
this.length = length;
this.width = width;
}
public int getLength(){
return length;
}
public int getWidth(){
return width;
}
public int getRadius(){
// Not applicable
return 0;
}
public double getArea(){
return width * length;
}
}
class Square implements Shape{
int length;
public Square(int length){
this.length = length;
}
public int getLength(){
return length;
}
public int getWidth(){
// Not applicable
return 0;
}
public int getRadius(){
// Not applicable
return 0;
}
public double getArea(){
return length * length;
}
}
class Circle implements Shape{
int radius;
public Circle(int radius){
this.radius = radius;
}
public int getLength(){
// Not applicable
return 0;
}
public int getWidth(){
// Not applicable
return 0;
}
public int getRadius(){
return radius;
}
public double getArea(){
return 3.14* radius * radius;
}
}
public class InterfaceNoSeggration{
public static void main(String args[]){
Rectangle r = new Rectangle(10,20);
Square s = new Square(15);
Circle c = new Circle(2);
System.out.println("Rectangle area:"+r.getArea());
System.out.println("Square area:"+s.getArea());
System.out.println("Circle area:"+c.getArea());
}
}
output:
java InterfaceNoSeggration
Rectangle area:200.0
Square area:225.0
Circle area:12.56
Notes:
Shape is a general purpose fat interface, which contains methods required for all Shape implementations like Rectangle, Circle and Square. But only some methods are needed in respective Shape childs
Rectangle : getLength(), getWidth(), getArea()
Square : getLength() and getArea()
Circle : getRadius() and getArea()
In absence of segregation, all Shapes have implemented entire fat interface : Shape.
We can achieve same output with interface segregation principle if we change the code as follows.
interface Length{
public int getLength();
}
interface Width{
public int getWidth();
}
interface Radius{
public int getRadius();
}
interface Area {
public double getArea();
}
class Rectangle implements Length,Width,Area{
int length;
int width;
public Rectangle(int length, int width){
this.length = length;
this.width = width;
}
public int getLength(){
return length;
}
public int getWidth(){
return width;
}
public int getRadius(){
// Not applicable
return 0;
}
public double getArea(){
return width * length;
}
}
class Square implements Length,Area{
int length;
public Square(int length){
this.length = length;
}
public int getLength(){
return length;
}
public int getWidth(){
// Not applicable
return 0;
}
public int getRadius(){
// Not applicable
return 0;
}
public double getArea(){
return length * length;
}
}
class Circle implements Radius,Area{
int radius;
public Circle(int radius){
this.radius = radius;
}
public int getLength(){
// Not applicable
return 0;
}
public int getWidth(){
// Not applicable
return 0;
}
public int getRadius(){
return radius;
}
public double getArea(){
return 3.14* radius * radius;
}
}
public class InterfaceSeggration{
public static void main(String args[]){
Rectangle r = new Rectangle(10,20);
Square s = new Square(15);
Circle c = new Circle(2);
System.out.println("Rectangle area:"+r.getArea());
System.out.println("Square area:"+s.getArea());
System.out.println("Circle area:"+c.getArea());
}
}
Notes:
Now individual Shapes like Rectangle, Square and Circle have implemented only required interfaces and got rid of un-used methods.
Agree with both the answers above. Just to give an example of TrueWill's code smell above, you shouldn't find yourself doing this:
#Override
public void foo() {
//Not used: just needed to implement interface
}
IWorker Interface:
public interface IWorker {
public void work();
public void eat();
}
Developer Class :
public class Developer implements IWorker {
#Override
public void work() {
// TODO Auto-generated method stub
System.out.println("Developer working");
}
#Override
public void eat() {
// TODO Auto-generated method stub
System.out.println("developer eating");
}
}
Robot Class:
public class Robot implements IWorker {
#Override
public void work() {
// TODO Auto-generated method stub
System.out.println("robot is working");
}
#Override
public void eat() {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("cannot eat");
}
}
For a more complete example go here.
Here's a real-world example of this principle (in PHP)
Problem Statement:
I want various forms of content to have comments/discussion associated with them. That content might be anything from a forum topic, to a news article, to a user's profile, to a conversation-style private message.
Architecture
We will want a re-usable DiscussionManager class which attaches a Discussion to a given content entity. However, the above four examples (and many more) are all conceptually different. If we want the DiscussionManager to use them, then all four+ need to have one common interface that they all share. There is no other way for DiscussionManager to use them unless you want to your arguments to go naked (e.g. no type checking).
Solution: Discussable interface with these methods:
attachDiscussion($topic_id)
detachDiscussion()
getDiscussionID()
Then DiscussionManager might look like this:
class DiscussionManager
{
public function addDiscussionToContent(Discussable $Content)
{
$Discussion = $this->DiscussionFactory->make( ...some data...);
$Discussion->save() // Or $this->DiscussionRepository->save($Discussion);
$Content->attachDiscussion($Discussion->getID()); // Maybe saves itself, or you can save through a repository
}
public function deleteDiscussion(Discussable $Content)
{
$id = $Content->getDiscussionID();
$Content->detatchDiscussion();
$this->DiscussionRepository->delete($id);
}
public function closeDiscussion($discussion_id) { ... }
}
This way, DiscussionManager does not care about any of the unrelated behaviors of the various content types that it uses. It ONLY cares about the behaviors it needs, regardless of what those behaviors are associated with. So by giving each content type that you want to have discussions for, a Discussable interface, you are using the interface segregation principle.
This is also a good example of a situation where an abstract base class is not a good idea. A forum topic, user profile, and news article aren't even remotely conceptually the same thing, thus trying to get them to inherit the discussion behaviors leads to strange coupling to an unrelated parent. Using a specific interface that represents discussions, you can makes sure that the entities you want to have discussions, are compatible with the client code that will be managing those discussions.
This example might also be a good candidate for usage of Traits in PHP, for what it's worth.

Passing an array of interfaces from C# to C++/CLI

I am trying to pass an array of interfaces from C# to C++/CLI. Here is the code:
// *** SafeArrayTesting_PlusPlus.cpp ***
#include "stdafx.h"
#include <comdef.h>
using namespace System;
using namespace System::Runtime::InteropServices;
namespace SafeArrayTesting_PlusPlus {
public ref class MyCppClass
{
public:
MyCppClass();
~MyCppClass();
void SetMyInterfaces(
array<SafeArrayTesting_Sharp::MyInterface^>^ myInterfaces);
};
MyCppClass::MyCppClass(){}
MyCppClass::~MyCppClass(){}
void MyCppClass::SetMyInterfaces(array<SafeArrayTesting_Sharp::MyInterface^>^
myInterfaces)
{
// Create safearray
SAFEARRAY *safeArrayPointer;
SAFEARRAYBOUND arrayDim[1]; // one dimensional array
arrayDim[0].lLbound= 0;
arrayDim[0].cElements= myInterfaces->Length;
safeArrayPointer = SafeArrayCreate(VT_UNKNOWN,1,arrayDim);
// copy ints to safearray
for (long lo= 0;lo<myInterfaces->Length;lo++)
{
IntPtr myIntPtr = Marshal::GetIUnknkownForObject(myInterfaces[lo]);
SafeArrayPutElement(
safeArrayPointer,
&lo,
static_cast<void*>(myIntPtr)
);
}
// do something with the safearray here - area XX
}}
// *** SafeArrayTesting_Main.cs ***
using SafeArrayTesting_PlusPlus;
using SafeArrayTesting_Sharp;
namespace SafeArrayTesting_Main
{
class SafeArrayTesting_Main
{
static void Main()
{
var myCppClass = new MyCppClass();
MyInterface myInterface = new MyClass();
myCppClass.SetMyInterfaces(new[]{ myInterface });
}
}}
// *** SafeArrayTesting_Sharp.cs ***
using System;
using System.Runtime.InteropServices;
namespace SafeArrayTesting_Sharp
{
[ComVisible(true)]
public interface MyInterface
{
int MyInt { get; set; }
string MyString { get; set; }
DateTime MyDateTime { get; set; }
}
[ComVisible(true)]
public class MyClass : MyInterface
{
public int MyInt{get;set;}
public string MyString{get;set;}
public DateTime MyDateTime{get; set;}
}
// Just to please the compiler; bear with me.
class DummyClass { static void Main() { } }
}
As written here, the code runs and compiles cleanly. However, when running the "area XX" part, I get a System.Runtime.InteropServices.SEHException.
The XX code is just a single line which calls an auto-generated method accepting a SAFEARRAY pointer. Here is the declaration of this method (from a .tlh file):
virtual HRESULT __stdcall put_SafeArray (
/*[in]*/ SAFEARRAY * pRetVal ) = 0;
I actually think this method converts the SAFEARRAY back to a .NET array - it's all part of a conversion project my company is running at the time. So there is no alternative to using a SAFEARRAY.
Anyway, it would really surprise me if the code without the XX part is bug-free; I'm quite a novice when it comes to C++. Can you help me spot some of the problems? If anyone can suggest a better way of testing the validity of the SAFEARRAY that would also be a help.
(By the way, this is a more complex variation of the question SafeArrayPutElement method throws System.AccessViolationException , in which I was just passing an array of ints from C# to C++/CLI.)
Several problems. For one, you don't actually store a VARIANT in the array. This is ultimately not going anywhere, a SafeArray cannot store references to managed objects. The garbage collector moves objects around, it cannot see references held by unmanaged code so it cannot update the reference.
At best, you could create an array of VT_UNKNOWN or VT_DISPATCH. But you can't get the COM interface pointer for these managed objects, they are not [ComVisible]. When you fix that, you'd use Marshal.GetIDispatchForObject() or Marshal.GetIUnknownForObject() to get the interface pointer to store in the array.

How to persist an enum using NHibernate

Is there a way to persist an enum to the DB using NHibernate? That is have a table of both the code and the name of each value in the enum.
I want to keep the enum without an entity, but still have a foreign key (the int representation of the enum) from all other referencing entities to the enum's table.
Why are you guys over complicating this? It is really simple.
The mapping looks like this:
<property name="OrganizationType"></property>
The model property looks like this:
public virtual OrganizationTypes OrganizationType { get; set; }
The Enum looks like this:
public enum OrganizationTypes
{
NonProfit = 1,
ForProfit = 2
}
NHibernate will automatically figure it all out. Why type more than you need????
You can use the enum type directly: http://web.archive.org/web/20100225131716/http://graysmatter.codivation.com/post/Justice-Grays-NHibernate-War-Stories-Dont-Use-Int-If-You-Mean-Enum.aspx. If your underlying type is a string, it should use the string representation, if it is numeric, it will just use the numeric representation.
But your question wording sounds like you're looking for something different, not quite an enum. It seems that you want a lookup table without creating a separate entity class. I don't think this can be done without creating a separate entity class though.
An easy but not so beautiful solution:
Create an integer field with and set the mapping in the mapping file to the field.
Create a public property that uses the integer field.
private int myField;
public virtual MyEnum MyProperty
{
get { return (MyEnum)myField; }
set { myField = value; }
}
I am using NHibernate 3.2, and this works great:
type="NHibernate.Type.EnumStringType`1[[enum_full_type_name, enum_assembly]], NHibernate"
Not sure when the generic EnumStringType got added, though.
Try using a stategy pattern. Uou can then put logic into your inner classes. I use this quite alot espically when there is logic that should be contained in the "enum". For example the code below has the abstract IsReadyForSubmission() which is then implemented in each of the nested subclasses (only one shown). HTH
[Serializable]
public abstract partial class TimesheetStatus : IHasIdentity<int>
{
public static readonly TimesheetStatus NotEntered = new NotEnteredTimesheetStatus();
public static readonly TimesheetStatus Draft = new DraftTimesheetStatus();
public static readonly TimesheetStatus Submitted = new SubmittedTimesheetStatus();
//etc
public abstract int Id { get; protected set; }
public abstract string Description { get; protected set; }
public abstract bool IsReadyForSubmission();
protected class NotEnteredTimesheetStatus: TimesheetStatus
{
private const string DESCRIPTION = "NotEntered";
private const int ID = 0;
public override int Id
{
get { return ID; }
protected set { if (value != ID)throw new InvalidOperationException("ID for NotEnteredTimesheetStatus must be " + ID); }
}
public override string Description
{
get { return DESCRIPTION; }
protected set { if (value != DESCRIPTION)throw new InvalidOperationException("The description for NotEnteredTimesheetStatus must be " + DESCRIPTION); }
}
public override bool IsReadyForSubmission()
{
return false;
}
}
//etc
}