protected virtual methods in f# - f#

F# does not support the definition of protected methods. Here it is explained why
F# replaces virtualmethods with abstractmethods defined in abstract classes (see here).
I was wondering if there is a way to prevent access to abstract methods from outside the derived classes at all.

Like Patryk Ćwiek, I also don't think it's possible, but here's one alternative:
From Design Patterns we know that we should favour Composition over Inheritance. In my experience, everything you can do with Inheritance, you can also do with Composition. As an example, you can always replace Template Method with a Strategy.
A Template Method is a typical use of an abstract method, but if you replace it with a Strategy, you can (sort of) hide it from clients:
type Foo(strategy : IBar) =
member this.CreateStuff() =
// 1. Do something concrete here
// 2. Use strategy for something here
// 3. Do something else concrete here
// 4. Return a result
No outside client of Foo can invoke strategy, so that accomplishes the same goal as making a member protected.
You may argue that the original creator of Foo may keep a reference to strategy, and will still be able to invoke it. That's true, but protected members aren't really completely hidden either, because you can often derive from the class in question, which enables you to invoke the protected member.
Another point is that if you separate the creator of Foo from the client of Foo, the strategy will be unavailable to the client.

Related

F# and protected access modifier [duplicate]

Is there a better way of modeling data in F# to avoid needing it?
The protected modifier can be quite problematic in F#, because you often need to call members from a lambda expression. However, when you do that, you no longer access the method from within the class. This also causes confusion when using protected members declared in C# (see for example this SO question). If you could declare a protected member, the following code could be surprising:
type Base() =
protected member x.Test(a) = a > 10
type Inherited() =
inherit Base()
member x.Filter(list) =
list |> List.filter (fun a -> x.Test(a))
This code wouldn't work, because you're calling Test from a lambda function (which is a different object than the current instance of Test), so the code wouldn't work. I think this is tha main reason for not supporting the protected modifier in F#.
In F# you typically use implementation inheritance (that is, inheriting from a base class) much less frequently than in C#, so you shouldn't need protected as often. Instead, it is usually preferred to use interfaces (in the object-oriented F# code) and higher-order functions (in the functional code). However, it is difficult to say how to avoid the need for protected in general (other than by avoiding implementation inheritance). Do you have some specific example which motivated your question?
As to whether F# enables a better way of modeling data, signature files allow finer grained visibility decisions than internal does in C#, which is often very nice. See Brian's comment here for a little bit more explanation. This is independent of support (or lack thereof) for protected, though.

How to denote component lifetime when using convention-based registration?

I've read a lot on the subject of IoC containers and particularly Mark Seemann's blog posts, where he emphasises the importance of convention over configuration. I understand and agree with his point, but I wonder how best to mark out a class for an irregular lifetime?
For example, most of my services are registered with a Transient lifetime - but I want a particular service to be registered as a Singleton because it does some useful caching.
I have thought about using some custom attributes, but I have read arguments against this (because it puts composition logic in the class).
I have had this same debate with, for example, dependencies on configuration primitives. Ultimately I ended up using a parameter attribute because it worked in my case, but I feel that perhaps I didn't see the 'hidden dangers'.
It is common for an IoC container to allow you to specify the lifestyle of an object. SimpleInjector, for example, provides Transient and Singleton out of the box (and also allows the user to create a custom lifestyle class). With SimpleInjector it's as simple as:
container.Register<ISvc, Impl>(Lifestyle.Singleton);
or
container.Register<ISvc, Impl>(Lifestyle.Transient);
No need for polluting your classes with composition logic.
As for configuration primitives, a common practice is to put those behind an interface. I put my connection string behind an IDatabaseConfiguration interface, for example, and its implementation reads the value from web.config. I then inject that interface into my data services.
EDIT: Disregard above. Keeping it in so that comments make sense.
The following doesn't actually answer the question, but it may solve the problem that prompted the question. You said that the class does some useful caching, which clues me in on that it is taking on an additional responsibility. I would therefore recommend that you do not attempt to register that single implementation as a singleton, but instead create a decorator class around that implementation.
container.RegisterDecorator(
typeof(ICommandHandler<>),
typeof(CommandHandlerCacheDecorator<>),
Lifestyle.Transient,
x => { return /*some logic that looks for and
finds that one class you want
to decorate*/
});
The decorator needs to be a transient, because it will have a transient reference to the command it decorates. However, it could then access a separate singleton class (via dependency injection of course) or cache object that handles the actual caching.
EDIT: Examples to single out the one class to decorate. There are plenty of options depending on just how specific you want to be. Again this is with SimpleInjector, but I'm sure other containers have their own analogues.
//decorate a specific class
x => { return x.ImplementationType.FullName == "My.Commands.Web.SomeName"; }
//decorate all classes that share a certain namespace
x => { return x.ImplementationType.Namespace.EndsWith("Commands.Web"); }
//decorate all classes that implement the same interface
x => { return x.ImplementationType.IsInstanceOfType(typeof(ICouldCache)); }

A pragmatic view on private vs public

I've always wondered on the topic of public, protected and private properties. My memory can easily recall times when I had to hack somebody's code, and having the hacked-upon class variables declared as private was always upsetting.
Also, there were (more) times I've written a class myself, and had never recognized any potential gain of privatizing the property. I should note here that using public vars is not in my habit: I adhere to the principles of OOP by utilizing getters and setters.
So, what's the whole point in these restrictions?
The use of private and public is called Encapsulation. It is the simple insight that a software package (class or module) needs an inside and an outside.
The outside (public) is your contract with the rest of the world. You should try to keep it simple, coherent, obvious, foolproof and, very important, stable.
If you are interested in good software design the rule simply is: make all data private, and make methods only public when they need to be.
The principle for hiding the data is that the sum of all fields in a class define the objects state. For a well written class, each object should be responsible for keeping a valid state. If part of the state is public, the class can never give such guarantees.
A small example, suppose we have:
class MyDate
{
public int y, m, d;
public void AdvanceDays(int n) { ... } // complicated month/year overflow
// other utility methods
};
You cannot prevent a user of the class to ignore AdvanceDays() and simply do:
date.d = date.d + 1; // next day
But if you make y, m, d private and test all your MyDate methods, you can guarantee that there will only be valid dates in the system.
The whole point is to use private and protected to prevent exposing internal details of your class, so that other classes only have access to the public "interfaces" provided by your class. This can be worthwhile if done properly.
I agree that private can be a real pain, especially if you are extending classes from a library. Awhile back I had to extend various classes from the Piccolo.NET framework and it was refreshing that they had declared everything I needed as protected instead of private, so I was able to extend everything I needed without having to copy their code and/or modify the library. An important take-away lesson from that is if you are writing code for a library or other "re-usable" component, that you really should think twice before declaring anything private.
The keyword private shouldn't be used to privatize a property that you want to expose, but to protect the internal code of your class. I found them very helpful because they help you to define the portions of your code that must be hidden from those that can be accessible to everyone.
One example that comes to my mind is when you need to do some sort of adjustment or checking before setting/getting the value of a private member. Therefore you'd create a public setter/getter with some logic (check if something is null or any other calculations) instead of accessing the private variable directly and always having to handle that logic in your code. It helps with code contracts and what is expected.
Another example is helper functions. You might break down some of your bigger logic into smaller functions, but that doesn't mean you want to everyone to see and use these helper functions, you only want them to access your main API functions.
In other words, you want to hide some of the internals in your code from the interface.
See some videos on APIs, such as this Google talk.
Having recently had the extreme luxury of being able to design and implement an object system from scratch, I took the policy of forcing all variables to be (equivalent to) protected. My goal was to encourage users to always treat the variables as part of the implementation and not the specification. OTOH, I also left in hooks to allow code to break this restriction as there remain reasons to not follow it (e.g., the object serialization engine cannot follow the rules).
Note that my classes did not need to enforce security; the language had other mechanisms for that.
In my opinion the most important reason for use private members is hiding implementation, so that it can changed in the future without changing descendants.
Some languages - Smalltalk, for instance - don't have visibility modifiers at all.
In Smalltalk's case, all instance variables are always private and all methods are always public. A developer indicates that a method's "private" - something that might change, or a helper method that doesn't make much sense on its own - by putting the method in the "private" protocol.
Users of a class can then see that they should think twice about sending a message marked private to that class, but still have the freedom to make use of the method.
(Note: "properties" in Smalltalk are simply getter and setter methods.)
I personally rarely make use of protected members. I usually favor composition, the decorator pattern or the strategy pattern. There are very few cases in which I trust a subclass(ing programmer) to handle protected variables correctly. Sometimes I have protected methods to explicitly offer an interface specifically for subclasses, but these cases are actually rare.
Most of the time I have an absract base class with only public pure virtuals (talking C++ now), and implementing classes implement these. Sometimes they add some special initialization methods or other specific features, but the rest is private.
First of all 'properties' could refer to different things in different languages. For example, in Java you would be meaning instance variables, whilst C# has a distinction between the two.
I'm going to assume you mean instance variables since you mention getters/setters.
The reason as others have mentioned is Encapsulation. And what does Encapsulation buy us?
Flexibility
When things have to change (and they usually do), we are much less likely to break the build by properly encapsulating properties.
For example we may decide to make a change like:
int getFoo()
{
return foo;
}
int getFoo()
{
return bar + baz;
}
If we had not encapsulated 'foo' to begin with, then we'd have much more code to change. (than this one line)
Another reason to encapsulate a property, is to provide a way of bullet-proofing our code:
void setFoo(int val)
{
if(foo < 0)
throw MyException(); // or silently ignore
foo = val;
}
This is also handy as we can set a breakpoint in the mutator, so that we can break whenever something tries to modify our data.
If our property was public, then we could not do any of this!

Why isn't there a protected access modifier in F#?

Is there a better way of modeling data in F# to avoid needing it?
The protected modifier can be quite problematic in F#, because you often need to call members from a lambda expression. However, when you do that, you no longer access the method from within the class. This also causes confusion when using protected members declared in C# (see for example this SO question). If you could declare a protected member, the following code could be surprising:
type Base() =
protected member x.Test(a) = a > 10
type Inherited() =
inherit Base()
member x.Filter(list) =
list |> List.filter (fun a -> x.Test(a))
This code wouldn't work, because you're calling Test from a lambda function (which is a different object than the current instance of Test), so the code wouldn't work. I think this is tha main reason for not supporting the protected modifier in F#.
In F# you typically use implementation inheritance (that is, inheriting from a base class) much less frequently than in C#, so you shouldn't need protected as often. Instead, it is usually preferred to use interfaces (in the object-oriented F# code) and higher-order functions (in the functional code). However, it is difficult to say how to avoid the need for protected in general (other than by avoiding implementation inheritance). Do you have some specific example which motivated your question?
As to whether F# enables a better way of modeling data, signature files allow finer grained visibility decisions than internal does in C#, which is often very nice. See Brian's comment here for a little bit more explanation. This is independent of support (or lack thereof) for protected, though.

Default implementations of Abstract methods

I am dealing with a large codebase that has a lot of classes and a lot of abstract methods on these classes. I am interested in peoples opinions about what I should do in the following situation.
If I have a class Parent-A with an abstract method. There will only be 2 children. If Child-B implements AbstractMethodA but Child-B does not as it doesnt apply.
Should I
Remove the abstract keyword from parent and use virtual or dynamic?
Provide a empty implementation of the method.
Provide an implementation that raises an error if called.
Ignore the warning.
Edit: Thanks for all the answers. It confirmed my suspicion that this shouldn't happen. After further investigation it turns out the methods weren't used at all so I have removed them entirely.
If AbstractMethodA does not apply to Child-B, then Child-B should not be inheriting from Parent-A.
Or to take the contrapositive, if Child-B inherits from Parent-A, and AbstractMethodA does not apply to the child, then it should not be in the parent either.
By putting a method in Parent-A, you are saying that the method applies to Parent-A and all its children. That's what inheritance means, and if you use it to mean something different, you will end up in a serious dispute with your compiler.
[Edit - that said, Mladen Prajdic's answer is fine if the method does apply, but should do nothing for one or more of the classes involved. A method which does nothing is IMO not the same thing as a method which is not applicable, but maybe we don't mean the same thing by "doesn't apply"]
Another technique is to implement the method in Child-B anyway, but have it do something drastic like always returning failure, or throw an exception, or something. It works, but should be regarded as a bit of a bodge rather than a clean design, since it means that callers need to know that the thing they have that they're treating as Parent-A is really a child-B and hence they shouldn't call AbstractMethodA. Basically you've discarded polymorphism, which is the main benefit of OO inheritance. Personally I prefer doing it this way over having an exception-throwing implementation in the base class, because then a child class can't "accidentally" behave badly by "forgetting" to implement the method at all. It has to implement it, and if it implements it to not work then it does so explicitly. A bad situation should be noisy.
If implementation in descendants is not mandatory then you should go for 1+2 (i.e. empty virtual method in ancestor)
I think that, generally speaking, you shouldn't inherit from the abstract class if you are unable to implement all of the abstract methods in the first place, but I understand that there are some situations where it still makes senseto do that, (see the Stream class and its implementations).
I think you should just create implementations of these abstract methods that throw a NotImplementedException.
You can also try using ObsoleteAttribute so that calling that particular method would be a compile time error (on top of throwing NotImplementedException of course). Note that ObsoleteAttribute is not quite meant to be used for this, but I guess if you use a meaningful error message with comments, it's alright.
Obligatory code example:
[Obsolete("This class does not implement this method", true)]
public override string MyReallyImportantMethod()
{
throw new NotImplementedException("This class does not implement this method.");
}
make it virtual empty in base class and override it in children.
You could use interfaces. Then Child-A and Child-B can both implement different methods and still inherit from Parent-A. Interfaces work like abstract methods in that they force the class to implement them.
If some subclasses (B1, B2, ...) of A are used for a different subset of its methods than others (C1, C2, ...), one might say that A can be split in B and C.
I don't know Delphi too well (not at all :) ), but I thought that just like e.g. in Java and COM, a class can 'implement' multiple interfaces. In C++ this can only be achieved by multiply inheriting abstract classes.
More concrete: I would create two abstract classes (with abstract methods), and change the inheritance tree.
If that's not possible, a workaround could be an "Adapter": an intermediate class A_nonB_ with all B methods implemented empty (and yielding a warning on calling them), and A_nonC_. Then change the inheritance tree to solve your problem: B1, B2, ... inherit from A_nonC_ and C1, C2,... inherit from A_NonB_.

Resources