This question already has answers here:
Functional programming vs Object Oriented programming [closed]
(4 answers)
Closed 6 years ago.
Although this is a very basic question, would anyone please explain it with example. Where should we use functional programming and where object oriented?
The biggest difference between the two “schools of thought” concerns the relationship between data and operations on the data.
The central tenet of OOP is that data and the operations upon it are tightly coupled: An object owns its data and it owns the implementation of the operations on the data. It hides those from other objects via its interface, a collection of methods or messages it responds to. Thus, the central model for abstraction is the data itself, hidden as it is behind a small API in the form of its interface.
The central activity in OOP is composing new objects and extending existing objects by adding new methods to them.
The central tenet of FP is that data is only loosely coupled to functions. You can write different operations on the same data structure, and the central model for abstraction is the function, not the data structure. Functions hide their implementation, and the language’s abstractions speak to functions and they way they are combined or expressed, such as generic functions or combinators.
The central activity in FP is writing new functions.enter link description here
I would suggest to use oop everywhere.. :)
If you need some function you can create it with static function..
for example
<?php
ThisClass {
public static function thisFunction () {
echo "runned";
}
}
thisFunction () {
echo "runned";
}
ThisClass::thisFunction();
thisFunction();
?>
OOP is awesome.
You can organize your code by classes (each class duos its thing).
Definitely use oop everywhere.
Not grate answer but. yeah.. :)
Related
I've recently stumbled upon interesting question (or maybe only author's mistake) and I've started to question myself. After some research I have to say I am not 100% sure of my answer, so I would like to ask if my thinking is correct. The question is:
Describe object oriented programming paradigms
I was first thinking that this is polymorphism, inheritance, encapsulation, abstraction. But why there is multiple form? As I understood my answer is description of paradigm (single) not paradigms (plural). Did I miss something, or this is correct answer?
Basing my argument on definition of paradigm which is generally a pattern of doing something. The paradigms would be:
Abstraction
Encapsulation
Polymorphism
Inheritance.
You might want to check out what Alan Kay has to say about this: http://c2.com/cgi/wiki?AlanKaysDefinitionOfObjectOriented
The necessary excerpts from the link:
This definition is derived from early versions of Smalltalk (Smalltalk-72?), and rules 5 and 6 clearly show Smalltalk's Lisp heritage. Kay remarked as such, noting that rules 4-6 would mutate as Smalltalk developed.
EverythingIsAnObject.
Objects communicate by sending and receiving messages (in terms of objects).
Objects have their own memory (in terms of objects).
Every object is an instance of a class (which must be an object).
The class holds the shared behavior for its instances (in the form of objects in a program list)
To eval a program list, control is passed to the first object and the remainder is treated as its message.
"Alan Kay, considered by some to be the father of object-oriented programming, identified the following characteristics as fundamental to OOP:"
EverythingIsAnObject.
Communication is performed by objects communicating with each other, requesting that objects perform actions. Objects communicate by sending and receiving messages. A message is a request for action, bundled with whatever objects may be necessary to complete the task.
Objects have their own memory, which consists of other objects.
Every object is an instance of a class. A class simply represents a grouping of similar objects, such as integers or lists.
The class is the repository for behavior associated with an object. That is, all objects that are instances of the same class can perform the same actions.
So far, similar to 1-5 above. Rule 6 is different. The reference to lists is removed, instead we have:
Classes are organized into a singly-rooted tree structure, called the inheritance hierarchy. Memory and behavior associated with instances of a class are available to any class associated with a descendent in this tree structure.
It depends on the viewing angle, better to say on the granularity, or what do you want to compare or emphasize.
Object oriented programming is one programming paradigm among others. But then there are different categories of object oriented programming. It makes sense to call the plurality of them object oriented programming paradigms.
See https://en.wikipedia.org/wiki/Object-oriented_programming for a beautiful list of programming paradigms.
OOP has its roots in the late 1960s and early 1970s, and it was formally introduced in the late 1980s. The main proponents of OOP were Alan Kay, Bertrand Meyer, and Grady Booch.
The idea behind OOP is to represent real-world objects and their behavior in a computer program. This allows developers to write software that is more intuitive and easier to understand, as well as reuse code by creating objects that can be used in multiple applications.
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of objects, which can contain data and behavior. In OOP, objects interact with each other by sending messages, and objects can be grouped into classes, which define their shared behavior and data.
OOP has evolved over time, and its use has become widespread in the software industry. Today, several programming languages support OOP, including PHP, Java, Python, C++, Ruby, and more.
You can read further in this post: What is OOP - Object Oriented Programming
This question already has answers here:
Java Interfaces Methodology: Should every class implement an interface?
(13 answers)
Closed 7 years ago.
I have been doing OOP for a quite while and I got confused with usages of interfaces after an argument with a colleague few days before.
Basically, I have been using interfaces when I apply design patterns, especially when there are multiple classes implementing common features.
In my application, there is Hibernate layer and few Sevices classes as example UserService, CompanyService, etc.
The question was whether we keep, separate interfaces also for each Service classes. Such as UserServiceContract, CompanyContract and etc.
My colleague argument was, there is no need to have interfaces.
I came across that in this tutorial also, the author has used interfaces. But there is no common interface that implements several classes only once.
example interface implentation
The benefit of using the interfaces was in this situation, it improves the code structure. Yes, there is IDE features that show what methods available for a class. But, I still want to get your guys idea too about this.
When you are talking design patterns and best coding practices, needing is not what you should be asking yourself. You do not need most of what you do, at least not immediately. Of course you do not know whether you will need different implementations of that contract until you actually do. So this is not a question of what you need right now. This is a question of what you will wish you had later.
What you have seen in the link you posted is the D in SOLID: the Dependency Inversion Principle:
Depend on abstractions, not on implementations.
You are better safe than sorry, you know.
EDIT: Also, I would advise against sufixes for interfaces (or prefixes). If you will be using the interface instead of the implementation, make the interface's name clean. A common choice would be, in your case, UserService for the interface and UserServiceImpl for the implementation.
Can someone point me to examples of multiparadigm (object-functional) programming in F#?
I am specifically looking for examples which combine OO & functional programming. There's been a lot of talk about how F# is a hybrid language but I've not been able to find examples which demonstrate the example of multiparadigm programming.
Thanks
I made a small (600 lines) Tetris clone with F# that is Object Oriented using XNA. The code is old (uses #light) and isn't the prettiest code you will ever see but it's defiantly a mix of OOP and functional. It consists of ten classes. I don't think I pass any first class functions around but it's a good example of the F#'s functional power in programming the small.
MyGame - Inherits XNA main game class and is the programs entry point.
Board - Keeps track of pieces that are no longer moving and horizontal line completes.
UI - The UI only has two states (playing and main menu) handled by bool stateMenu
Tetris - Handles game state. Game over and piece collision.
Piece - Defines the different Tetris shapes and their movement and drawing.
Player - Handles user input.
Shape - The base graphic object that maps to primative.
Primative - Wraps the Vertex primitive type.
I made a rough class diagram to help. If you have any questions about it feel free to ask in the comment section.
There are two ways of combining the functional and object-oriented paradigm. To some extent, they are independent and you can write immutable (functional) code that is structured using types (written as F# objects). An F# example of Client type written like this would be:
// Functional 'Client' class
type Client(name, income) =
// Memebers are immutable
member x.Name = name
member x.Income = income
// Returns a new instance
member x.WithIncome(ninc) =
new Client(name, ninc)
member x.Report() =
printfn "%s %d" name income
Note that the WithIncome method (which "changes" the income of the client) doesn't actually do any modifications - it follows the functional style and creates a new, updated, client and returns it as the result.
On the other hand, in F# you can also write object-oriented code that has mutable public properties, but uses some immutable data structure under the cover. This may be useful when you have some nice functional code and want to expose it to C# programmers in a traditional (imperative/object-oriented) way:
type ClientList() =
// The list itself is immutable, but the private
// field of the ClientList type can change
let mutable clients = []
// Imperative object-oriented method
member x.Add(name, income) =
clients <- (new Client(name, income))::clients
// Purely functional - filtering of clients
member x.Filter f =
clients |> List.filter f
(The example is taken from the source code of Chapter 9 of my book. There are some more examples of immutable object-oriented code, for example in parallel simulation in Chapter 14).
The most powerful experience I've had mixing OO (specifically mutation) and functional programming is achieving performance gains by using mutable data-structures internally while enjoying all the benefits of immutability by external users. A great example is an implementation I wrote of an algorithm which yields lexicographical permutations you can find here. The algorithm I use is imperative at it's core (repeated mutation steps of an array) which would suffer if implemented with a functional data structure. By taking an input array, making a read-only copy of it initially so the input is not corrupted, and then yielding read-only copies of it in the sequence expression after the mutation steps of the algorithm are performed, we strike a fine balance between OO and functional techniques. The linked answer references the original C++ implementation as well as benchmarks other purely functional implementation answers. The performance of my mixed OO / functional implementation falls in between the superior performance of the OO C++ solution and the pure functional F# solution.
This strategy of using OO / mutable state internally while keeping pure externally to the caller is used throughout the F# library notably with direct use of IEnumerators in the Seq module.
Another example may be found by comparing memoization using a mutable Dictionary implementation vs. an immutable Map implementation, which Don Syme explores here. The immutable Dictionary implementation is faster but no less pure in usage than the Map implementation.
In conclusion, I think using mutable OO in F# is most powerful for library designers seeking performance gains while keeping everything pure functional for library consumers.
I don't know any F#, but I can show you an example of the exact language mechanics you're looking for in Scala. Ignore it if this isn't helpful.
class Summation {
def sum(aLow : Int, aHigh : Int) = {
(aLow to aHigh).foldLeft(0) { (result, number) => result + number }
}
}
object Sample {
def main(args : Array[String]) {
println(new Summation sum(1, 10))
}
}
I tried to keep it super simple. Notice that we're declaring a class to sum a range, but the implementation is used with a functional style. In this way, we can abstract the paradigm we used to implement a piece of code.
I don't know about F#, but most softwares written in Scala are object-functional in nature.
Scala compiler is probably the largest and a state of the art example of an object-functional software. Other notable examples include Akka, Lift, SBT, Kestrel etc. (Googling will find you a lot more object-functional Scala examples.)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Why do we use Interface?
Is it only for Standardization?
Purposes of Interfaces
create loosely coupled software
support design by contract (an implementor must provide the entire interface)
allow for pluggable software
allow different objects to interact easily
hide implementation details of classes from each other
facilitate reuse of software
Analogy 1: Much like the US space shuttle, Russian Soyuz spacecraft and Chinese Shenzhou 5 can all dock to the International Space Station, because they implement the same docking interface. (This is just an example - I don't know if it's true in real life however let's suspend our disbelief for the sake of an example)
Analogy 2: Like you can plug various computer monitors into your home computer. You can plug a wall-size TV into it, an old CRT (the thick kind), a 20" flat screen, or a braille machine for the blind to "see" by touch. There's compatibility among these various/different devices and your computer because they all agree on interface standards.
Details of C# interfaces --
With C#/OOP interfaces you're doing the same kind of thing but in the unseen/virtual world.
You're correct about standardization, but also flexibility, scalability, extensibility, maintainability, reusability, testability and power.
(The more you use software interfaces the more these "buzz words" will be understood. And always consider interfaces in the real world because they have done us equally well.)
An interface is used to describe what an implemented thing can do. So you have the possibility to treat several objects which implementing the same interface as a type of this interface.
For example:
public interface IMyInterface{
public void DoFirst();
public int DoSecond();
}
public class A : IMyInterface{
//class has to implement DoFirst and DoSecond
public void DoFirst(){
Console.WriteLine("Blubb1");
}
public int DoSecond(){
Console.WriteLine("Blubb2");
return 2;
}
}
public class B : IMyInterface{
//class has to implement DoFirst and DoSecond
public void DoFirst(){
Console.WriteLine("Blibb1");
}
public int DoSecond(){
Console.WriteLine("Blibb2");
return 4;
}
}
The classes implement the Interface in several ways. But you can use them as IMyInterface.
For example:
public static void DoMethodsInInterface(IMyInterface inter){
inter.DoFirst();
inter.DoSecond();
}
public static void main(){
DoMethodsInInterface(new A());
DoMethodsInInterface(new B());
//Or use it in a List
List<IMyInterface> interlist = new List<IMyInterface>();
interlist.Add(new A());
interlist.Add(new B());
foreach(IMyInterface inter in interlist){
inter.DoFirst();
}
}
I hope this makes a bit clear why interfaces are useful.
It's for interfacing :), so that you could interface between stuff, it's useful when you have
multiple implementations of same stuff
when you apply an interface to multiple different classes because you need some sort of convention that these classes are goonna be able to do some stuff or have some functionality
Here's the high level view...
Interfaces play a big role in the concept of Information Hiding.
They basically help you hide the implementation details of your class so that a calling class does has no dependency on that implementation. Therefore, by using interfaces you can modify the implementation without changing the calling class. This all in turns limits the complexity of your code and make it easier to maintain in the long run.
When I first started understanding interfaces they were explained to me as a "contract that provides a description your class." Not sure if that will help you but if you think of an interface for a car you could say that it drives, breaks, and turns. So as long as it gets me from point A to point B, I don't really have to know how those functions are implemented.
The main reason the interfaces are used in languages like C#/Java is because those languages don't support multiple (class) inheritance (see What is the exact problem with multiple inheritance?).
But multiple (interface) implementation is permited allowing classes to be used in diferent ways.
Interfaces are somewhat awkward.
They support design by contract just by believing, that same name and implemented interface means the same behaviour. This works only thanks to API documentation, it has to be human-checked. That makes interfaces too weak. One way to get around that could be formal specs.
On the other hand, interfaces are too strong, too strict. You cannot evolve interfaces which often gets in the way of reuse. This is solved by protocols - mechanism in dynamic languages, which send messages(call methods) and when that message is not supported by receiver, standard callback gets called.
Having concrete protocols with constraints would be imho better.
Think remoting...
There is a client and a server involved here. Lets say they are physically separated by the internet. The client is calling a method whose actual execution happens on the server. From the client's perspective the client doesn't know anything about the object in the server which performs the execution. However it knows what method to call. Because while building the client program, we are only exposed to an interface (or contract). We are not exposed to the whole object which is actually living on the server. Try doing some demo apps in .net remoting, and you'll figure the rest. Happy programming.
Why do we use interfaces?
Some languages implement polymorphic method calls using vtables and discard most of the type information making it hard not to define interfaces.
So sometime we simply use interfaces because the language design requires it.
By starting with an interface, you can implement a proxy, thus allowing for lazy loading or performing some verifications when calling the methods of a concrete implementation.
Interface separates the data type from the implementation logic.
Interface provide prototype modal that just contains declaration of functionality of a specific behavior.
and if u want to implement this behavior into class then u must implement this interface in class then class have this behavior functionality or it can have multiple behavior.
because class can implement multiple interface.
If anyone else is like me and learns by example and doing, rather than only explanation, here is some code....
I found this implementation of a Neural Network in C#, including project download, which makes use of Interfaces in an elegant and useful manner:
http://www.c-sharpcorner.com/UploadFile/rmcochran/AI_OOP_NeuralNet06192006090112AM/AI_OOP_NeuralNet.aspx
I am interested in improving my designing capability (designing of classes with its properties, methods etc) for a given.
i.e. How to decide what should be the classes, methods and properties?
Can you guys suggest me good material for improving on this?
Please see:
Any source of good object-oriented design practises?
Best Resources to learn OO Design and Analysis
among many....
Encapsulation: The wrapping up of data and functions into a single unit is known as encapsulation. Or, simply put: putting the data and methods together in a single unit may be a class.
Inheritance: Aquiring the properties from parent class to child class. Or: getting the properties from super class to sub class is known as inheritance.
Polymorphism: The ability to take more that one form, it supports method overloading and method overriding.
Method overloading: When a method in a class having the same method name with different arguments (diff parameters or signatures) is said to be method overloading. This is compile-time polymorphism – using one identifier to refer to multiple items in the same scope.
This is perhaps a question which every programmer thinks of one day.
The designing capability comes with your experience gradually. What I would say is in general scenario if you can visualize the Database objects for a given problem, the rest is a cakewalk (isnt true sometimes if you work on a techie project with no DB)
You can start thinking of objects which are interacting in the real world to complete the process and then map them to classes with appropriate properties and then methods for defining their behavior. Ten you can focus on the classes which contribute to running the workflow and not to any individual real world object.
This gets a lot simplified if we focus on designing the DB before we jump directly to code design.
A lot depends on the pattern you choose - If you see a problem from MVC perspective, you will naturally be drawn towards identifying "controller" classe first and so on.
I guess I need not repeat the golden sources of design and OOPS wisdom - they already posted here or there.
I would recommend you to read up on some UML and design patterns. That gets you going with the thinking in "drawing" terms. You can also get a good grasp of a big class/object a lot easier.
One particular book that is good in this area.
Applying UML and Patterns
Give a look a Domain-Driven Design, which defines entities, value objects, factories, services and repositories and the GRASP patterns (General Responsibility Assignment Software Patterns) e.g. Expert, Creator, Controller.
Have a look at the part 1 screencast the first part is not silverlight but just a command line calculator that starts out as a single bit of code, and is then broken down into classes.