How can I define class methods OUTSIDE of the class' brackets to improve readability? - class

How can I define class methods OUTSIDE of the class' brackets to improve readability? E.g., something similar to this...
class MyClass {
//Private variables:
int _foo = 0;
//Private methods:
void _incrementFoo();
//Public methods:
int getFoo();
}
void _incrementFoo() {
_foo++;
}
int getFoo() {
_incrementFoo();
return _foo--;
}
As you can see, I would like to tell the class about the methods by providing a signature, then I would actually define them outside of the class... Any way to do this in dart?

Well, I don't agree that what you want to do would improve the readability. If you want to split the interface and implementation I think the following are a lot better:
abstract class MyClass {
//Public methods:
int getFoo();
factory MyClass() => _MyClass();
}
class _MyClass implements MyClass {
//Private variables:
int _foo = 0;
//Private methods:
void _incrementFoo() => _foo++;
//Public methods implementation:
int getFoo() => _foo;
}
If you really want to do it you way you need to have a way to tell you method that they are part of you class. You could do something like this:
class MyClass {
//Private variables:
int _foo = 0;
//Private methods:
void _incrementFoo() => _incrementFooImpl(this);
//Public methods:
int getFoo() => getFooImpl(this);
}
void _incrementFooImpl(MyClass myClass) {
myClass._foo++;
}
int getFooImpl(MyClass myClass) {
myClass._incrementFoo();
return myClass._foo--;
}
But I think this is rather ugly and you are ending up adding a lot of global methods in your code which can make it hard to see which class each method are belonging to.

Related

Dart: Inherit some of the public methods privately

I want to inherit a class, but I want to make some of its methods private, which allows mutation of the object. I do not want to override those methods, as that will make them still accessible and cause a runtime error. I want something like this:-
class BaseClass {
//...
void update() {/*Implementation*/}
void read() {/*Implementation*/}
}
class ChildClass extends BaseClass {
//...
void read() {/*Implementation*/}
}
int main() {
final first = BaseClass(), second = ChildClass();
first.update(); //Works
second.update(); //Error: Method does not exist.
}
I don't think what you want it possible. The entire point of extending classes is that child classes can access all public methods of the superclass. You might want to use composition instead. That would be something like:
class BaseClass {
//...
void update() {/*Implementation*/}
void read() {/*Implementation*/}
}
class ChildClass {
BaseClass _baseClass
//...
void read() { _baseClass.read() }
}

Haxe access Class<T> static fields

I have three classes and I would like to be able to call static functions from the returned Class<Access>. I would like to select class type based on conditions.
class Access {
public static function get(item: Int): Int { return -1; }
public static function getAccessType(): Class<Access> {
if(Client.hasConnection())
return Remote;
else return Local;
}
}
class Remote extends Access {
override public static function get(item: Int): Int { return Server.getItem(item); }
}
class Local extends Access {
override public static function get(item: Int): Int { return Client.getItem(item); }
}
You can't override a static function in Haxe.
But you can probably achieve what you're trying to do by simply removing the override in Remote and Local
Can be done with singletons.
However, still the question might relevant whether such feature in Haxe even exists.
Depending on target, you may be able to cast a class to an interface/typedef to pull out values in a type-safe-ish way. "override" does not work for static methods
class Test {
static function pick(z:Bool):HasGetItem {
return z ? cast A : cast B;
}
static function main() {
trace("Haxe is great!");
trace(pick(false).getItem(1));
trace(pick(true).getItem(2));
}
}
#:keep class A {
public static function getItem(i:Int):Int return 10;
}
#:keep class B {
public static function getItem(i:Int):Int return 5;
}
typedef HasGetItem = {
getItem:Int->Int
}
https://try.haxe.org/#b2b87

How do I pass a parameter to the constructor using Simple Injector?

Does Simple Injector allow you to pass parameters to constructor when you resolve? I'd like to know if both these frameworks do what Unity's ResolverOverride or DependencyOverride both do.
I suspect that this question is about passing primitive values to the constructor at the time the service is actually resolved.
Let's set up a simple test class:
public interface IFoo
{
}
public class Foo : IFoo
{
public Foo(string value)
{
}
}
The Foo class takes a string argument that we would like to supply when resolving the IFoo service.
var container = new ServiceContainer();
container.Register<string, IFoo>((factory, value) => new Foo(value));
var firstFoo = container.GetInstance<string, IFoo>("SomeValue");
var secondFoo = container.GetInstance<string, IFoo>("AnotherValue");
If we want to be able to create new instances of the Foo class without using the container directly, we can simply inject a function delegate.
public interface IBar { }
public class Bar : IBar
{
public Bar(Func<string, IFoo> fooFactory)
{
var firstFoo = fooFactory("SomeValue");
var secondFoo = fooFactory("AnotherValue");
}
}
The "composition root" now looks like this:
var container = new ServiceContainer();
container.Register<string, IFoo>((factory, value) => new Foo(value));
container.Register<IBar, Bar>();
var bar = container.GetInstance<IBar>();
If the question is about passing a "static" primitive value to the contructor, this is simply done by registering a factory delegate like this.
var container = new ServiceContainer();
container.Register<IFoo>((factory) => new Foo("SomeValue"));
var firstInstance = container.GetInstance<IFoo>();
var secondInstance = container.GetInstance<IFoo>();
The difference is that this approach does not let you pass a value at resolve time. The value is statically specified at registration time.
Probably the easiest option with Simple Injector is to register with a delegate
[Test]
public void Test1()
{
Container container = new Container();
container.Register<IClassWithParameter>(() => new ClassWithParameter("SomeValue"));
var result = container.GetInstance<IClassWithParameter>();
}
public interface IClassWithParameter { }
public class ClassWithParameter : IClassWithParameter
{
public ClassWithParameter(string parameter)
{
}
}
An advanced option for injecting primitive dependencies is detailed here
The above will all work if your constructor does not have any other dependencies (or you want to resolve these dependencies manually). If you have the scenario below though it falls down:
public class Test : ITest
{
private IFoo _foo;
public Test(string parameter, IFoo foo)
{
_foo = foo;
....
}
}
Now you not only have to manually inject the string but also Foo. So now your not using dependancy injection at all (really). Also Simple Injector state:
Simple Injector does not allow injecting primitive types (such as
integers and string) into constructors.
My reading of this is that they're saying "don't do this".
Extensibillity points
Another option here is to use "Extensibillity points" for this scenario.
To do this you need to abstract your hard coded elements from your injected elements:
public class Test : ITest
{
private IFoo _foo;
public Test(IFoo foo)
{
_foo = foo;
....
}
public void Init(string parameter)
{
}
}
You can now inject your dependanices and your hardcoded elements:
_container.Register<ITest, Test>();
_container.RegisterInitializer<Test>(instance => {instance.Init("MyValue");});
If you now add another dependancy, your injection will now work without you having to update the config, i.e. your code is nicely de-coupled still:
public class Test : ITest
{
private IFoo _foo;
private IBar _bar;
public Test(IFoo foo, IBar bar)
{
_foo = foo;
_bar = bar;
....
}
public void Init(string parameter)
{
}
}
In response to Liam's answer I would like to point out that there is a simpler way of doing this.
If you have the following situation:
public class Test : ITest
{
private IFoo _foo;
public Test(IFoo foo, string parameter)
{
_foo = foo;
....
}
}
You could write your ioc configuration as below
_container.Register<IFoo, Foo>();
_container.Register<ITest>(
() => new Test(
_container.GetInstance<IFoo>(),
"MyValue"
)
);

C++/CLI: Cannot explicitly implement interface member with different return type

Let's say we have two C++/CLI interfaces declaring Foo() members with different return type.
public interface class InterfaceA
{
bool Foo();
};
public interface class InterfaceB
{
int Foo();
};
What we want to do here is to have a class that instantiates an object that can be accessed through the above interfaces. So, the straight forward way to do that would be:
public ref class Class : InterfaceA, InterfaceB
{
virtual bool Foo() = InterfaceA::Foo { return true; }
virtual int Foo() = InterfaceB::Foo { return 10; }
};
Unfortunately that gives us compiler error "overloaded function differs only by return type from". Is there any workaround for this C++/CLI limitation?
No, you have to rename the method. For example:
public ref class Class : InterfaceA, InterfaceB
{
public:
virtual bool Foo() { return true; }
virtual int Foo2() = InterfaceB::Foo { return 10; }
};
Note how this is never a real problem. If code has a reference to Class instead of the interface for some reason then it can always call InterfaceB::Foo() with a cast:
Class^ obj = gcnew Class;
safe_cast<InterfaceB^>(obj)->Foo();

Cast a CustomList<CustomClass> to IList<Interface>

(This is .Net 3.5) I have a class FooList which implements IList and a class FooClass which implements IFoo. A user requires IList<IFoo>. In my implementation, I create a FooList<FooClass>, called X. How do I code my return so that my FooList<FooClass> X becomes his IList<IFoo>?
If I try
return X.Cast( ).ToList( );
he gets an IList<IFoo>, but it is not my FooList; it is a List, and a new one at that.
This isn't going to work out, because a FooList<FooClass> is not an IList<IFoo>. This is why:
var myList = new FooList<FooClass>();
IFoo obj = new SomeOtherFooClass();
IList<IFoo> result = (IList<IFoo>)myList; // hypothetical, wouldn't actually work
result.Add(obj); // uh-oh, now myList has SomeOtherFooClass
You need to either make a copy or use an interface that is actually covariant on the contained type, like IEnumerable<T> instead of IList<T>. Or, if appropriate, you should declare your FooList<FooClass> as an FooList<IFoo> from the get-go instead.
Here is a small implementation that demonstrates my second suggestion:
public interface IFoo { }
public class FooClass : IFoo { }
public class FooList<T> : IList<T>
{
public void RemoveAt(int index) { /* ... */ }
/* further boring implementation of IList<T> goes here */
}
public static void ListConsumer(IList<IFoo> foos)
{
foos.RemoveAt(0); // or whatever
}
public static IList<IFoo> ListProducer()
{
// FooList<FooClass> foos = new FooList<FooClass>(); // would not work
FooList<IFoo> foos = new FooList<IFoo>();
foos.Add(new FooClass());
return foos; // a FooList<IFoo> is an IList<IFoo> so this is cool
}
public static void Demo()
{
ListConsumer(ListProducer()); // no problemo
}