I have been to many interviews, where always a question interviewers used to ask "Do you know virtual function?"
I always wonder why experienced programmer/developer use function with virtual. As much I know.. not all functions can be virtual, only those functions which are part of any class/struct can be virtual.
So I think "Function is superset and method is subset. Not all functions can be methods but, all methods are functions. Therefore it would be appropriate to use "virtual method" not "virtual function".
Can somebody explain, why most of the experienced programmer and even technical books write use "virtual function" not "virtual method"?
Technically methods are those that belong to classes and functions are the ones that don't, but like with other things that are so general and common, people end up mixing up the terminology and in the end "function" and "method" can both refer to one thing or the other. That's pretty much the answer to your question... In the end, terminology is defined by how people use it, not by the original intended meanings.
Perhaps this link can help you :-
http://www.dotnet-tricks.com/Tutorial/oops/4a0J170612-Difference-between-function-and-method.html
Yes, linguistically or logically the functions are not the part of the class, but methods are the members of the class.
Or, in more simple words, methods don't have their own existence, they belong to class. But the functions have their own existence.
I hope this might also have clarified your doubts.
Related
I'm making a method inside a Ruby on Rails app called "print" that can take any string and converts it into a png. I've been told it's not good to make class methods for base ruby classes like String or Array or Hash, etc. so "some string to print".print is probably not something I should do.
I was thinking about making a subclass of String called Print (class Print < String) and storing it in my lib/assets folder. So it would look like: Print.new("some string to print"). So my question is, am I on the right track by 1) creating a sub-class from String and 2) storing it in lib/assets?
Any guidance would be greatly appreciated!
Answers to your question will necessarily be subjective because there are always be many answers to "where should I put functionality?", according to preference, principle, habit, customs, etc. I'll list a few and describe them, maybe add some of my personal opinions, but you'll ultimately have to choose and accept the consequences.
Note: I'll commonly refer to the common degenerate case of "losing namespacing scope" or "as bad as having global methods".
Monkeypatch/Extend String
Convenient and very "OO-message-passing" style at the cost of globally affecting all String in your application. That cost can be large because doing so breaks an implicit boundary between Ruby core and your application and it also scatters a component of "your application" in an external place. The functionality will have global scope and at worst will unintentionally interact with other things it shouldn't.
Worthy mention: Ruby has a Refinements feature that allows you to do do "scoped monkeypatching".
Worthy mention 2: Ruby also lets you includes modules into existing classes, like String.class_eval { include MyCustomization } which is slightly better because it's easier to tell a customization has been made and where it was introduced: "foo".method(:custom_method).owner will reveal it. Normal Monkeypatching will make it as if the method was defined on String itself.
Utils Module
Commonly done in all programming languages, a Util module is simply a single namespace where class methods/static methods are dumped. This is always an option to avoid the global pollution, but if Util ends up getting used everywhere anyways and it gets filled to the brim with unrelated methods, then the value of namespacing is lost. Having a method in a Util module tends to signify not enough thought was put into organizing code, since without maintenance, at it's worst, it's not much better than having global methods.
Private Method
Suppose you only need it in one class -- then it's easy to just put it into one private method. What if you need it in many classes? Should you make it a private method in a base class? If the functionality is inherent to the class, something associated with the class's identity, then Yes. Used correctly, the fact that this message exists is made invisible to components outside of that class.
However, this has the same downfall as the Rails Helper module when used incorrectly. If the next added feature requires that functionality, you'll be tempted to add the new feature to the class in order to have access to it. In this way the class's scope grows over time, eventually becoming near-global in your application.
Helper Module
Many Rails devs would suggest to put almost all of these utility methods inside rails Helper modules. Helper modules are kind of in between Utils Module and Private Method options. Helpers are included and have access to private members like Private Methods, and they suggest independence like Utils Modules (but do not guarantee it). Because of these properties, they tend to end up appearing everywhere, losing namespacing, and they end up accessing each other's private members, losing independence. This means it's more powerful, but can easily become much worse than either free-standing class/static methods or private methods.
Create a Class
If all the cases above degenerate into a "global scope", what if we forcibly create a new, smaller scope by way of a new class? The new class's purpose will be only to take data in and transform it on request on the way out. This is the common wisdom of "creating many, small classes", as small classes will have smaller scopes and will be easier to handle.
Unfortunately, taking this strategy too far will result in having too many tiny components, each of which do almost nothing useful by themselves. You avoid the ball of mud, but you end up with a chunky soup where every tiny thing is connected to every other tiny thing. It's just as complicated as having global methods all interconnected with each other, and you're not much better off.
Meta-Option: Refactor
Given the options above all have the same degenerate case, you may think there's no hope and everything will always eventually become horribly global -- Not True! It's important to understand they all degenerate in different ways.
Perhaps functionality 1, 2, 3, 4... 20 as Util methods are a complete mess, but they work cohesively as functionality A.1 ~ A.20 within the single class A. Perhaps class B is a complete mess and works better broken apart into one Util method and two private methods in class C.
Your lofty goal as an engineer will be to organize your application in a configuration that avoids all these degenerate cases for every bit of functionality in the system, making the system as a whole only as complex as necessary.
My advice
I don't have full context of your domain, and you probably won't be able to communicate that easily in a SO question anyways, so I can't be certain what'll work best for you.
However, I'll point out that it's generally easier to combine things than it is to break them apart. I generally advise starting with class/static methods. Put it in Util and move it to a better namespace later (Printer?). Perhaps in the future you'll discover many of these individual methods frequently operate on the same inputs, passing the same data back and forth between them -- this may be a good candidate for a class. This is often easier than starting off with a class or inheriting other class and trying to break functionality apart, later.
While hearing talk around the objective-c programming community, I hear the term "override" thrown around a lot. I'm fairly familiar with general object oriented programming terms, but from an iOS and Objective-c standpoint, the definition is a little unclear to me. According to Wikipedia:
Method overriding, in object oriented programming, is a language
feature that allows a subclass or child class to provide a specific
implementation of a method that is already provided by one of its
superclasses or parent classes.
Cool. That makes sense. But what throws me off is... isn't that the whole point of the "family relationship", where the subclass inherits all of the public methods and variables of it's superclass. The standard "hierarchy" model. That has never quite made sense to me. I hear some of the senior developers say things such as "Once he said it's okay to override a category I was done listening".
That got me to thinking, I should probably get a better grasp on what exactly overriding is. Could someone explain it in greater detail related specifically to Objective-C / Cocoa Touch?
This is very common in all OOP languages.
Often times a base class will provide a default (i.e. simple, unexciting) implementation for a method. Then, derived classes will override that default implementation and provide a specific (i.e. more interesting) implementation.
Consider an Animal base class that exposes a Speak() method. Well there is no common way that animals speak, so that default implementation would probably just do nothing.
A Dog class, which is derived from Animal, can override Speak() to actually make a barking sound, which is more appropriate than the default mute case.
Your quote from your senior seems to me like it's mis-heard or -remembered. I'd bet it was "...it's okay to override a method in a category I was done..."
Using a category to "override" a method on the same class is a Bad Idea: the original method is clobbered and cannot be called. In addition, if the original method was itself implemented in a category, then which version is actually used is undefined. This is not the same as overriding an inherited method (thus my scare quotes).
Overriding an inherited method works as expected: a class defines a method which was already defined in one of its ancestors. When the method is called on an instance of the subclass, the redefined code is run. The class itself can invoke the non-overridden version by using the super keyword as the receiver of the appropriate message.
This is a very elementary question about the F# class syntax. Here is a little code to illustrate my problem.
type AClass() as self =
member this.Something = printfn "Hello"
Basically from what I have read the "as self" will create a name to the current instance which can be used in the entire class (like "this" in C# or Java). But "member this.Something" will do the same thing, only that the scope is limited to the method body. I guess I can see when you would use which syntax. The "as self" one can be used if you need it in the constructor or something and you can use the other one if you dont need it in the constructor.
But why do I have to use the "member this.Something" syntax even if I used the "as self" one? Why does it give me an error if I just write "member Something"? What have I missed?
Take care,
Kerr
The scope of as self is the whole class, while scope of this.Something is just an individual method. You don't often need as self since using this.Something is adequate.
Regarding why you need this. in member declaration, I think it's a natural choice since in F# classes you often have let bounds and static methods as well. Having self as default would cause confusion and misuse.
Here is an example using as self in MSDN, which is not common IMO:
type MyClass2(dataIn) as self =
let data = dataIn
do
self.PrintMessage()
member this.PrintMessage() =
printf "Creating MyClass2 with Data %d" data
It sounds like you've got all the differences between global 'as xxx' and member 'yyy.' instance binding sorted out. So I guess the answer to your answer has to be it's "by design".
Folks will argue that there is a deliberate rational behind this "by design" choice, but after 4 years of programming F#, my favorite language by far, I have personally not found it very helpful in any regard.
I suspect that the real reason the language requires explicit instance bindings to variables is because is more closely reflects the underlying .NET CIL implementation. That is, languages like C# bind "this" to the instance of a class definition as a feature. Under-the-hood, both static and instance methods of a class are called in the same manner using the Call and CallVirt opcodes, where in the case of instance methods the address of "this" is loaded as the first argument to the call.
But we've certainly ventured into the territory of taste and opinion.
I don't think this is duplication at all. self's visibility to the entire class is a by-product of F#'s "intelligent" compilation of primary constructors. The constructor's arguments/bindings can be implicitly compiled to both local and member (class-level) fields. The as identifier syntax merely facilitates this references within that mutant context. I'd venture to guess, if unused, it's compiled away. Otherwise, all you've done is stored an extra reference to this as a member field (which would seem bizarre in another language, such as C#).
The problem is whether an instance method should in anyway alter the object that contains the method or should it return a new instance? I'm new to F# and the concept of full mmutability that is suggested for F#.
Just using psuedo code for now unless I need to be more specific.
First thought is just add the message to the message list on the object:
class Something
ctr(messages)
_messages.Add(messages)
AddMessage(message)
_messages.Add(message)
Second is to construct a new list that joins the old list and the new message. Then I would create a new instance altogther and send back.
class Something
ctr(messages)
_messages.Add(messages)
AddMessage(message)
newMessageList = _messages.Join(message)
return new Something(newMessageList)
Am I overthinking immutability?
In my opinion, the answer depends on your requirements. The immutable style is probably more idiomatic, and would be a sensible default. However, one nice thing about F# is that you can choose what to do based on your needs; there's nothing inherently wrong with code that uses mutation. Here are some things to consider:
Sometimes the mutable approach leads to better performance, particularly when used in a single-threaded context (but make sure to measure realistic scenarios to be sure!)
Sometimes the immutable approach lends itself better to use in multi-threaded scenarios
Sometimes you want to interface with libraries that are easier to use with imperitave code (e.g. an API taking a System.Action<_>).
Are you working on a team? If so, are they experienced C# developers? Experienced F# developers? What kind of code would they find easiest to read (perhaps the mutable style)? What kind of code will you find easiest to maintain (probably the immutable style)?
Are you just doing this as an exercise? Then practicing the immutable style may be worthwhile.
Stepping back even further, there are a few other points to consider:
Do you really even need an instance method? Often, using a let-bound function in a module is more idiomatic.
Do you really even need a new nominal type for what you're doing? If it's just a thin wrapper around a list, you might consider just using lists directly.
As you are doing "class based" programming which is one of the way (rather unfortunate) to do object oriented programming, you would be doing in place state modification rather than returning a new state (as that's what would be expected when you are doing OO).
In case you really want to go towards immutability then I would suggest you need to use more FP concepts like Modules, Functions (not methods which have you have in class based programming), recursive data types etc.
My answer is way too general and the appropriate answer lies in the fact that how this class of your will fit in the big picture of your application design.
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_.