r/dailyprogrammer • u/Coder_d00d 1 3 • Jul 14 '14
[Weekly #2] Pre-coding Work
Weekly Topic #2:
What work do you do before coding your solution? What kind of planning or design work if any do you do? How do you do it? Paper and pencil? Draw a picture? Any online/web based tools?
Give some examples of your approach to handling the dailyprogrammer challenges and your process that occurs before you start coding.
Last week's Topic:
[Weekly Topic #1] (http://www.reddit.com/r/dailyprogrammer/comments/2a3pzl/weekly_1_handling_console_input/)
70
Upvotes
View all comments
Show parent comment
4
u/skeeto -9 8 Jul 15 '14 edited Jul 15 '14
OO is entirely compatible with functional programming. Functional-style OO treats objects as immutable values, and methods will return new objects rather than mutate the target object. Classes are for grouping values together as a new type of value, and methods are functions that can be specialized for one (single dispatch) or more (multiple dispatch) specific types.
Here's an example in Common Lisp, which combines functional and OO style via CLOS. Define a 2D vector class with two read-only numeric fields, x and y.
In Common Lisp methods don't belong to classes. They're functions specialized to specific types of objects/values. The
defclassabove creates two methods,xandy, specialized for accessing the slots on vec2 objects. The followingmagnitudeanddotmethods are also specialized to vec2.Here's a
normalizemethod that returns a new vec2 object as a normalized version of its argument.Now define the same methods for a vec3 class. Note that I'm not bothering with inheritance (the empty parens after the class name).
Here's the cool part: define an
angle-betweenfunction that computes the angle between two vectors of the same dimension. It uses methods, but it's not actually a method itself, yet it will work with any type with reasonable definitions fordotandnormalize(duck typing), such as some future vec4 class.This is all functional-style programming, since there's no statefulness and everything is a value -- and it's also OO, since we're defining classes and methods to operate on those classes.
Your maps are really just structs without a formally-declared type. They're like anonymous structs. JavaScript, and any language prototype-based OO, works like this. All objects are just maps. Classes are not formally declared to the language. Instead, methods -- functions assigned to keys on the map -- are just looked up on the maps themselves along with everything else.
The advantage of a declared struct would be:
As a final note: in my opinion, you can't practically build large systems without some form of OOP. Encapsulation and polymorphism is too essential. If your language doesn't support it, then you'll end up spinning your own (i.e. the Linux kernel with C). Is there any large, complex piece of software on your computer not primarily using OOP?