Execute an objects method without making a new instance - object

How can I execute Print from within TestObject?
class Program
{
private int Value;
static void Main()
{
TestObject test = new TestObject();
Program p1 = new Program();
Program p2 = new Program();
p1.Value = 1;
p2.Value = 2;
p1.Print();
p2.Print();
}
private void Print()
{
Console.Write(Value.ToString());
Console.ReadKey();
}
}
class TestObject
{
// How to execute p1.Print here?
}

There are multiple ways to do this:
Pass Program directly to TestObject
Pros:
Simple change
Cons:
You will have to make Print public
You will expose other things in Program
You're coupling TestObject to Program directly
Here's sample code:
class Program
{
static void Main()
{
TestObject test = new TestObject(this);
}
public void Print()
{
Console.Write(Value.ToString());
Console.ReadKey();
}
}
class TestObject
{
public TestObject(Program p)
{
p.Print();
}
}
Pass a delegate to TestObject
Pros:
Simple change
Doesn't have to make Print public
Only exposes 1 method to TestObject
Cons:
The coupling is TestObject wants to do something, not TestObject wants access to something that does something
Here's sample code:
class Program
{
static void Main()
{
TestObject test = new TestObject(() => Print());
}
private void Print()
{
Console.Write(Value.ToString());
Console.ReadKey();
}
}
class TestObject
{
public TestObject(Action print)
{
print();
}
}
Implement an interface in Program and pass it to TestObject
Pros:
Only exposes what the interface exposes
Easier to implement other places (better to say "need this interface" than "needs a delegate", clearer contract specification)
No coupling to a specific type, coupling is to any object that meets certain criteria - implements an interface
Cons:
None relevant (in my opinion)
Here's sample code:
interface IPrintable
{
void Print();
}
class Program : IPrintable
{
static void Main()
{
TestObject test = new TestObject(this);
}
public void Print()
{
Console.Write(Value.ToString());
Console.ReadKey();
}
}
class TestObject
{
public TestObject(IPrintable p)
{
p.Print();
}
}
Conclusion: My advice would be to pick the interface way. Clearer design, easier to extend without having multiple delegates being passed around.

Related

C# Class implementation with generics

Hi everyone I am studying C# but ran into some compiler errors:
I am getting the error: 'LinkedList' does not implement interface member 'IEnumerable.GetEnumerator()'
I think I did.
Below is the code:
using System;
using System.Collections.Generic;
namespace LinkedListGenericsExample
{
public class LinkedListNode<T>
{
//constructor
public LinkedListNode(T value)
{
//code here
}
//code here
}
//LinkedList class with generics. It inherit the IEnumerable class with
//generics. Should I use IEnumerable or IEnumerable<T>?
public class LinkedList<T>: IEnumerable<T>
{
//code here
}
public LinkedListNode<T> AddLast(T node)
{
//code here
}
public IEnumerator<T> GetEnumerator()
{
//code here
}
//here I think the GetEnumerator() method is implemented
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
//Trying this but not working. Also I am confused.
/*
IEnumerator IEnumerable<T>.GetEnumerator()
{
return GetEnumerator();
}
*/
//Main() below
}
I am using the Visual Studio Code to compile the code.
Error ecountered:
'LinkedList' does not implement interface member 'IEnumerable.GetEnumerator()'
Using the generic type 'IEnumerator' requires 1 type arguments
Using the generic type 'IEnumerable' requreis 1 type arguments
'IEnumerable' in explicit interface declaration is not an interface
Question:
1) Should I inherit the IEnumerable class or IEnumerable class with generic?
2) How can I implement the "IEnumerable.GetEnumerator()" It looks like the compiler is not recognized my GetEnumerator() implementation but I am not sure why....
Need some help here. Thank you!
Updating the complete code below. It works!!
using System;
using System.Collections; //using System.Collections instead
namespace LinkedListGenericsExample
{
//Linked list node class in Generics form
public class LinkedListNode<T>
{
//LinkedListNode constructor
public LinkedListNode(T value)
{
this.Value = value;
}
public T Value;
public LinkedListNode<T> Next {get; internal set;}
public LinkedListNode<T> Prev {get; internal set;}
}
public class LinkedList<T>: IEnumerable
{
public LinkedListNode<T> First {get; private set;}
public LinkedListNode<T> Last {get; private set;}
public LinkedListNode<T> AddLast(T node)
{
var newNode = new LinkedListNode<T>(node);
if (First == null)
{
First = newNode;
Last = First;
}
else
{
Last.Next = newNode;
Last = newNode;
}
return newNode;
}
public IEnumerator GetEnumerator()
{
LinkedListNode<T> current = First;
while(current != null)
{
yield return current.Value;
current = current.Next;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/*
IEnumerator IEnumerable<T>.GetEnumerator()
{
}
*/
}
class Program
{
static void Main(string[] args)
{
//Console.WriteLine("Hello World!");
var list2 = new LinkedList<int>();
var list3 = new LinkedList<String>();
list2.AddLast(1);
list2.AddLast(3);
list2.AddLast(5);
//Go throuhg entire list of numbers
foreach(int i in list2)
{
Console.WriteLine(i);
}
Console.WriteLine();
list3.AddLast("2");
list3.AddLast("four");
list3.AddLast("foo");
//Go through entire list of strings
foreach(string s in list3)
{
Console.WriteLine(s);
}
}
}
}
Regarding your two questions, here are 2 cents.
1. I would suggest you implement the generic version. This would ensure type-safety and other benefits. You can read more on advantages of generics in this link. . Since you are learning C#, it would be a good idea to read about it.
Your implementation looks good.Please add reference to System.Collections namespace to your code for fixing the compile errors.
using System.Collections;

Creating anonymous object with inline function. Does it contain a leak of Enclosing Class?

As you know each anonymous object in java contains hidden reference to enclosing class.
But with kotling things get more complicated.
Lambda is another representation of anonymous class, but in kotlin it compiles not straightforward, because if lambda didn't capture a reference of enclosing class explicitely than it would be compiled like nested, not inner class (anonymous class) and is safe from the leak.
But what about inline functions. Consider the code below
class A {
fun test(){
val it = withReference {
//todo make sth
}
}
}
inline fun withReference(crossinline action: () -> Unit) = object: Reference {
override fun method1() {
action()
}
override fun method2() {
}
}
interface Reference {
fun method1()
fun method2()
}
As i know inline function would be compiled like non-wrapped code to the A class, so the question is open.
Does the anonymous object: Reference contain a link to enclosing class A, which could lead to a memory leak?
PS: i have read this article, but it doesn't contain an answer to my case
I used the decompiler of IntelliJ and there is no reference to the outer A
public final class A$test$$inlined$withReference$1 implements Reference {
public void method1() {
}
public void method2() {
}
}
If the lambda references a variable from the outer class A like this:
class A {
val valFromA = 10;
fun test(){
val it = withReference {
println("use $valFromA")
}
}
}
Then the decompiler shows the reference to the A object:
public final class A$test$$inlined$withReference$1 implements Reference {
// $FF: synthetic field
final A this$0;
public A$test$$inlined$withReference$1(A var1) {
this.this$0 = var1;
}
public void method1() {
String var1 = "use " + this.this$0.getValFromA();
System.out.println(var1);
}
public void method2() {
}
}
If you think about it, the withReference function has no way of referring to the outer scope that it gets inlined into, therefore it has no reason to contain a reference to the scope that it's called from. You don't even know what class it's being called in, or if it's even called inside a class, for that matter.
For this specific case, here's the decompiled and simplified bytecode of the withReference function:
public static Reference withReference(final Function0 action) {
return new Reference() {
public void method1() {
action.invoke();
}
public void method2() {
}
};
}
At the places where it gets inlined, there's of course no call to this function, this one is for Java interop only. Kotlin call sites all get their own class generated to represent this object depending on what code you pass into the action parameter. For your call of the test function, a class like is generated:
public final class A$test$$inlined$withReference$1 implements Reference {
public void method1() {
//todo make sth
}
public void method2() {
}
}
And this is what's instantiated in the test method:
public final class A {
public final void test() {
Reference it = new A$test$$inlined$withReference$1();
}
}

Groovy Inner Classes wont work with Apache Wicket

Im trying to write simple things with Apache Wicket (6.15.0) and Groovy (2.2.2 or 2.3.1). And Im having trouble with inner classes.
class CreatePaymentPanel extends Panel {
public CreatePaymentPanel(String id) {
super(id)
add(new PaymentSelectFragment('currentPanel').setOutputMarkupId(true))
}
public class PaymentSelectFragment extends Fragment {
public PaymentSelectFragment(String id) {
super(id, 'selectFragment', CreatePaymentPanel.this) // problem here
add(new AjaxLink('cardButton') {
#Override
void onClick(AjaxRequestTarget target) {
... CreatePaymentPanel.this // not accessible here
}
})
add(new AjaxLink('terminalButton') {
#Override
void onClick(AjaxRequestTarget target) {
... CreatePaymentPanel.this // not accessible here
}
});
}
} // end of PaymentSelectFragment class
} // end of CreatePaymentPanel class
Groovy tries to find a property "this" in CreatePaymentPanel class.. How to workaround this? It is a valid java code, but not groovy.
However,
Test.groovy:
class Test {
static void main(String[] args) {
def a = new A()
}
static class A {
A() {
def c = new C()
}
public void sayA() { println 'saying A' }
class B {
public B(A instance) {
A.this.sayA()
instance.sayA()
}
}
/**
* The problem occurs here
*/
class C extends B {
public C() {
super(A.this) // groovy tries to find property "this" in A class
sayA()
}
}
}
}
Above code wont work, the same error occurs, like in Wicket's case.
And TestJava.java, the same and working:
public class TestJava {
public static void main(String[] args) {
A a = new A();
}
static class A {
A() {
C c = new C();
}
public void sayA() {
System.out.println("saying A");
}
class B {
public B(A instance) {
instance.sayA();
}
}
/**
* This works fine
*/
class C extends B {
public C() {
super(A.this);
sayA();
}
}
}
}
What I am missing?
You can't refer to a CreatePaymentPanel.this inside of PaymentSelectFragment because there is no instance of CreatePamentPanel that would be accessible there. What would you expect that to evaluate to if it were allowed?

How is IClock resolved with SystemClock in this example?

I am trying to learn IOC principle from this screencast
Inversion of Control from First Principles - Top Gear Style
I tried do as per screencast but i get an error while AutomaticFactory try create an object of AutoCue. AutoCue class has contructor which takes IClock and not SystemClock. But my question is , in screencast IClock is resolved with SystemClock while inside AutomaticFactory .But in my code , IClock does not get resolved . Am i missing something ?
class Program
{
static void Main(string[] args)
{
//var clarkson = new Clarkson(new AutoCue(new SystemClock()), new Megaphone());
//var clarkson = ClarksonFactory.SpawnOne();
var clarkson = (Clarkson)AutomaticFactory.GetOne(typeof(Clarkson));
clarkson.SaySomething();
Console.Read();
}
}
public class AutomaticFactory
{
public static object GetOne(Type type)
{
var constructor = type.GetConstructors().Single();
var parameters = constructor.GetParameters();
if (!parameters.Any()) return Activator.CreateInstance(type);
var args = new List<object>();
foreach(var parameter in parameters)
{
var arg = GetOne(parameter.ParameterType);
args.Add(arg);
}
var result = Activator.CreateInstance(type, args.ToArray());
return result;
}
}
public class Clarkson
{
private readonly AutoCue _autocue;
private readonly Megaphone _megaphone;
public Clarkson(AutoCue autocue,Megaphone megaphone)
{
_autocue = autocue;
_megaphone =megaphone;
}
public void SaySomething()
{
var message = _autocue.GetCue();
_megaphone.Shout(message);
}
}
public class Megaphone
{
public void Shout(string message)
{
Console.WriteLine(message);
}
}
public interface IClock
{
DateTime Now { get; }
}
public class SystemClock : IClock
{
public DateTime Now { get { return DateTime.Now; } }
}
public class AutoCue
{
private readonly IClock _clock;
public AutoCue(IClock clock)
{
_clock = clock;
}
public string GetCue()
{
DateTime now = _clock.Now;
if (now.DayOfWeek == DayOfWeek.Sunday)
{
return "Its a sunday!";
}
else
{
return "I have to work!";
}
}
}
What you basically implemented is a small IoC container that is able to auto-wire object graphs. But your implementation is only able to create object graphs of concrete objects. This makes your code violate the Dependency Inversion Principle.
What's missing from the implementation is some sort of Register method that tells your AutomaticFactory that when confronted with an abstraction, it should resolve the registered implementation. That could look as follows:
private static readonly Dictionary<Type, Type> registrations =
new Dictionary<Type, Type>();
public static void Register<TService, TImplementation>()
where TImplementation : class, TService
where TService : class
{
registrations.Add(typeof(TService), typeof(TImplementation));
}
No you will have to do an adjustment to the GetOne method as well. You can add the following code at the start of the GetOne method:
if (registrations.ContainsKey(type))
{
type = registrations[type];
}
That will ensure that if the supplied type is registered in the AutomaticFactory as TService, the mapped TImplementation will be used and the factory will continue using this implementation as the type to build up.
This does mean however that you now have to explicitly register the mapping between IClock and SystemClock (which is a quite natural thing to do if you're working with an IoC container). You must make this mapping before the first instance is resolved from the AutomaticFactory. So you should add the following line to to the beginning of the Main method:
AutomaticFactory.Register<IClock, SystemClock>();

Strategy Pattern or Interface?

I'm looking to abstract a helper method. The method needs to be able to take in an object, do things with it depending on the type of object, and return a value. Would it be better to do something like this:
interface ICanDo
{
string DoSomething();
}
string DoThings(ICanDo mything)
{
return mything.DoSomething();
}
Or is it better to do something like this:
interface IStrategy
{
string DoSomething(object o);
}
string DoThings(object mything, IStrategy strategy)
{
return strategy.DoSomething(mything);
}
Is the latter even using a strategy pattern, since the strategy isn't being built into the class?
Is there a better way to do this I'm not thinking of? Would it be better to build the strategy into the class, using a wrapper for any class that needs to have DoThings run on it?
Sorry--I'm new to this pattern and trying to figure out where and how to use it best.
This is what I ended up putting together. I'm unsure if this follows good development principles.
class IndexWrapper
{
public interface IDocumentable
{
Document BuildDocument();
}
public interface IDocumentBuilder
{
Type SupportedType { get; }
Document BuildDocument(object o);
}
public class StringDocumentBuilder : IDocumentBuilder
{
public Type SupportedType { get { return typeof(string); } }
public Document BuildDocument(object o)
{
Document doc = new Document();
doc.Add(new Field("string", o as string, Field.Store.YES, Field.Index.ANALYZED));
return doc;
}
}
public static class IndexableFactory
{
public static IDocumentable GetIndexableObject(object o)
{
return GetIndexableObject(o, DocumentBuilderFactory.GetBuilder(o));
}
public static IDocumentable GetIndexableObject(object o, IDocumentBuilder builder)
{
return new IndexableObject(o, builder);
}
}
public static class DocumentBuilderFactory
{
private static List<IDocumentBuilder> _builders = new List<IDocumentBuilder>();
public static IDocumentBuilder GetBuilder(object o)
{
if (_builders.Count == 0)
{
_builders = Assembly.GetExecutingAssembly()
.GetTypes()
.Where(type => typeof(IDocumentBuilder).IsAssignableFrom(type) && type.IsClass)
.Select(type => Activator.CreateInstance(type))
.Cast<IDocumentBuilder>()
.ToList();
}
return _builders.Where(builder => builder.SupportedType.IsAssignableFrom(o.GetType())).FirstOrDefault();
}
}
private class IndexableObject : IDocumentable
{
object _o;
IDocumentBuilder _builder;
public IndexableObject(object o) : this(o, DocumentBuilderFactory.GetBuilder(o)) { }
public IndexableObject(object o, IDocumentBuilder builder)
{
_o = o;
_builder = builder;
}
virtual public Document BuildDocument()
{
return _builder.BuildDocument(_o);
}
}
}
When in doubt, keep the KISS mantra in your mind - Keep It Short and Simple. Patterns can be very useful, but often they're only useful in specific cases and add unnecessary complexity otherwise.
In my experience, the strategy pattern is useful for when you have multiple different backends to choose from for a class. For example, say you have a logging class that your program uses to print debug information. Maybe in some cases, you want to log to a file. Maybe you'd like to log to a console. Perhaps you'd even like to log to a remote server with a proprietary protocol you company made!
So, your logging class may look like this:
interface IOutputWriter
{
void WriteLn(string message);
}
class ConsoleWriter : IOutputWriter
{
public ConsoleWriter()
{
}
public void WriteLn(string message)
{
Console.WriteLine(message);
}
}
class NetworkWriter : IOutputWriter
{
public NetworkWriter()
{
}
public void WriteLn(string message)
{
//Crazy propietary server protocol action
}
}
class Logger
{
IOutputWriter writer;
public Logger(IOutputWriter writer)
{
this.writer = writer;
}
public void Log(string message)
{
writer.WriteLn(message + "Date");
}
}
With the end result that your program code looks like this:
class Program
{
static void Main(string[] args)
{
Logger logger = new Logger(new ConsoleWriter());
logger.Log("Test");
}
}
The benefit is that if you want to use your crazy networking protocol, you can do it without even looking at the logging class. You just have to make a new class with your IOutputWriter interface and tell your logger to use your custom backend. The strategy pattern is essentially defining reusable interfaces and then using those interfaces to decouple algorithms from each other.

Resources