Object Oriented vs Procederal

Status
Not open for further replies.

NavyGothic

Ars Legatus Legionis
10,397
Subscriptor
For the vast majority of programming tasks, things like maintainability, reliability, security, extensibility (and other exciting keywords!) are more important than raw performance.

That's not to say that performance is irrelevant, but if using a modern fully managed language like C# gets us to 90% of the optimal, then the advantages of working in a higher level language far outweigh the performance impact.

There are times where performance is absolutely critical (for example, a game engine might run a particular collision detection function a gazillion times per second), and that's when it makes sense to optimise at a low level; sometimes even down to assembly.
 

MilleniX

Ars Tribunus Angusticlavius
8,140
Subscriptor++
It sounds like you've taken intro CS classes that have each used a different one of those languages? If that's the case, that's not really "quite a bit of computer science as a whole". Rather, that's the same year of computer science, repeated 4 times. The reason I say this is that you express what I [1] see as a naive focus on a tiny facet of program 'goodness', namely how allocation behavior bears on performance.

Going solely from that, there are much bigger issues that matter to how programs perform. If I'm searching for one object in a collection of 1 million, a linear search (e.g. a for loop from the beginning of an array to its end) will potentially examine all of them, and half of them on average. In contrast, a binary search will examine at most 21 entries. This notion of algorithmic performance, and the data structures that support it, can appear in any programming language.

More broadly speaking, though, yes, higher-level languages provide more convenience, but they too can actually provide performance benefits that are unavailable without the associated abstractions and restrictions. The stricter the type system, the more the language implementation knows about each entity in your program. In Java and C#, for instance, it's common for the implementation to look at what implementation of a virtual method is actually being invoked at a particular call site, and optimize by specialization to that case. With just function pointers in a C struct, the compiler is never going to spit out anything better than an indirect jump instruction and move on.

Higher level languages also encode a great deal of this expertise in the abstractions they provide. One of the best examples I can give is Python's dictionary type. The programmer writes code to feed it a pile of key/value pairs that they'll want to look up later, and doesn't care what it does with them. When you ask for one particular element, you'll run code that the people who implemented Python have spent immense effort optimizing because this is an incredibly important, hugely common operation. There could be tricks that you might never dream of, hiding in production-grade implementations of what look like garden-variety data structures, because those convenient abstractions mean that you're using shared infrastructure.

Basically, if you write everything yourself, from scratch, your code will only ever be as good as the expertise you possessed and applied when you wrote it. If you build on the foundations laid by others, any increase in their capabilities will mean that you'll reach higher, without putting in proportionally more thought or effort. So, if you want your work to have an impact, either take advantage of all of the automatic expertise that's already out there, or start contributing to it. Reinventing the wheel will never build you a rocket to the moon.

[1] ABD PhD student in computer science, working on parallel runtime system and application development. In what I work on, I do have to care not just about memory allocation, but memory layout as well, so that related bits of data have the right structural relationship to be nice to caches. However, until something takes so much time or energy to run that users are impacted by it, or exceeds the resources available, none of that shit matters. Human attention is better spent on the bits of code that are actually costing you something.
 

Ben_H

Ars Scholae Palatinae
1,059
[url=http:/civis/viewtopic.php?p=26064587#p26064587:1ke3i95n said:
MilleniX[/url]":1ke3i95n]
Higher level languages also encode a great deal of this expertise in the abstractions they provide. One of the best examples I can give is Python's dictionary type. The programmer writes code to feed it a pile of key/value pairs that they'll want to look up later, and doesn't care what it does with them. When you ask for one particular element, you'll run code that the people who implemented Python have spent immense effort optimizing because this is an incredibly important, hugely common operation. There could be tricks that you might never dream of, hiding in production-grade implementations of what look like garden-variety data structures, because those convenient abstractions mean that you're using shared infrastructure.

Basically, if you write everything yourself, from scratch, your code will only ever be as good as the expertise you possessed and applied when you wrote it. If you build on the foundations laid by others, any increase in their capabilities will mean that you'll reach higher, without putting in proportionally more thought or effort. So, if you want your work to have an impact, either take advantage of all of the automatic expertise that's already out there, or start contributing to it. Reinventing the wheel will never build you a rocket to the moon.
I'm only a lowly Junior year undergrad CS person, but this discussion is coming up daily in my high level languages class and it is quite fascinating. We are looking at Haskell and we have been discussing this exact concept with regards to comparing how Haskell does things compared to languages like C. My professor (his PhD was in Language design, particularly to do with higher level languages) often mentions that since some of these high level languages are becoming so efficient, the amount of time saved using them (though they require a lot more understanding and at first before you can use them effectively, and a bit of math in some cases) is becoming increasingly worthwhile as program complexity increases. If you can do a 100 line C program in only 10 lines in Haskell and the performance difference is marginal, then obviously it would be superior to use Haskell for this task because of the amount of time saved making the thing. When we get to vastly larger projects, this applies even more so. Not to mention that we know that the stuff we are using within the language will definitely work compared to if we implement things ourselves, not to mention probably in a much more efficient fashion.

As he says, the geniuses already figured out how to make all this stuff in these languages work. We might as well take advantage of it and save ourselves some work.

There's a reason past first year they let you use libraries for data structures rather than having to implement them yourself.
 

jbode

Ars Legatus Legionis
11,752
Subscriptor
Some solutions are simply easier to visualize as a collection of objects rather than as a collection of functions. For example, I find concurrency (multithreading) to be much easier to deal with when using an OO approach as opposed to a procedural one. YMMV.

Don't knock "programmer convenience"; development time is the biggest cost driver in software development. Performance matters, but other things matter more: it doesn't matter how fast your code is if it does the wrong thing or gives you the wrong answer, or if it blows up because someone looks at it funny, or if it's an unmaintainable sludge of source text. Using standard containers instead of rolling your own saves you development and testing time. It makes your code easier to analyze and verify. It's also one less thing to look at when the inevitable bug reports come in from the field.
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
Why not have functions with the required data in the function?

Functions themselves have data*** only in so far as they are given it to start with (their arguments), or that they create themselves locally (assuming there is something that boils down to call scope - i.e. local variables you might naively consider to be 'on the stack') plus global state (but everything gets access to global state so it's not overly interesting, or a good thing to do in many cases).

The whole point of objects in OO is to make data which would be useful to the function, but whose lifespan may not correspond to an individual invocation of the function something simply[1] accessible within the function. OO is by no means the only way to do this. Closures are another way to do it, and if you look behind the scenes a closure and an object are pretty much indistinguishable in terms of how they might be implemented (Many languages with support for both implement the one with the other).

There are benefits to doing it via OO if:
Multiple functions would benefit from sharing the same data (closures can also do this but it becomes quite a bit harder to spot this dependency as the complexity rises[2]).
The life cycle of the shared data may be complex[3].
Also it may well be desirable to *name* and specify the function(s) in some manner. This is normally something made difficult/impossible in functional and procedural languages. There is value to naming a thing (as well as costs), most especially when it changes.
However, the absolute slam dunk reason for using an object is if the data has *invariants* which the function's correctness depends on. In that case the class may take whatever actions are necessary on construction, and within the functions to maintain these invariants. It is better not to need such things, but sometimes it is reasonable to require it, and to do it in a clear and controlled fashion (doing so via closures becomes very messy, very fast).
You can view the rise of bounds checked arrays in many modern languages as a reified object (hich contains the reference to where data begins, the length of the data (perhaps the type of the data) and methods to access and set the nth element of the data. Heavily wrapped up in sugar, heavily optimised, and occasionally abused for performance by certain parts of the system, but none the less an object. Neatly such an object can be used by many other functions using only a limited subset of those operations it exposes, therefore it may be desirable for them to stop operating on the object as an array, instead operating on it as something that only provides those operations (interfaces and abstract classes would be on 'OO' way to do this, late binding would be a way to do it in dynamic ones, duck typing another)

That said there is plenty of code that requires no such state, or which would be more flexible in future if such state was passed as arguments rather than on construction. If an OO language discourages/makes harder simply making functions/procedures to perform this it is not ideal. An example of this is that java and c# (currently) disallow functions from being defined except as Methods (forcing the OO aspect to the fore). This has some upsides (commonality of naming, and thus selecting the functions, plus a reliable and simple instrospection API). It does however limit the flexibility of the language in terms of what can be done in a REPL, something java and c# have definitely realised to their cost.

There's nothing stopping a language have OO capabilities but not require it (Scala, F#, ML, perl[4] for example), Including many OO languages ruby for example allow free functions by having a top level self or class.

*** it is possible to define a language such that the function has data (accessible only to repeated invocations of it) but this is functionally identical to wrapping every function in an object that holds this data, or if mixed with normal OO adding fields to the object which are in scope only within the function. Such a language might be interesting from a technical point of view, but it's just function objects, so pure sugar for the purposes of this discussion.

1. Behind the scenes it may well be anything but, but normally this is entirely abstracted away from the end user by a nice pointer/reference called self/this/My whatever.
2. Much less so if you are in a language with immutability be default.
3. implementing 'proper' closure support (C++ isn't really proper since the environment is not captured arbitrarily, only for a limited period of validity) with some form of memory management is incredibly difficult.
4. perl can do OO - doing so makes me want to swear, YMMV of course

That last bit should be *without some form of automatic memory management* doh
 
Sometimes it seems making the object with an allocator and a deallocator and all it entails would be very costly compared to just writing a function.

OO is an organizational principle. It is a principle that is convenient for grouping a set of functions that all operate on the same data structure. It so happens that in real world programming there frequently arise such groups of functions that need to work on the same data structure. In theory there is no performance penalty for organizing your code in an object-oriented fashion. To my knowledge, however, only C++ actually implements this abstraction cost-free. Most other languages introduce another layer of indirection in the reference to your data structure which is poison to the optimizer but this is not necessary. Most other languages also implement "methods" as function pointers which is actually horrible for the optimizer (no function in-lining) but also not integral to the idea of object orientation.

Edit: From my point of view, and the other side has a coherent argument to make too, lifecycle management is not the core idea of object orientation and is in fact orthogonal.
 
[url=http:/civis/viewtopic.php?p=26069963#p26069963:39pj8dz7 said:
AbstractDonut[/url]":39pj8dz7]
And yet one of the things they used during class was to make structures, queues, stacks, lists, out of pointers or linked lists. The more I learned about programming now I've learned that for performance a linked list will never compare to a straight array.
Well, that's just not true. Linked lists are faster at growing/shrinking than C arrays. Linked lists are also persistent data structures and can avoid most copying overhead.

Concurrency is very important when you get down to that level. C with pointer arithmetic and being able to malloc a size of memory and treat it as an array shows this off much better than I've seen in any of the other languages.
I think it's not overstating the case that if you have multiple threads accessing the same mutable array, you're almost certainly doing it wrong.

So I guess what I'm saying Objects seem very inefficient to me when you are making simple stuff. You want to make just one object you don't want to make huge lists of objects and that is what all the higher languages seem to encourage you to do.
That's probably true, but who wants to make simple stuff? If it's simple enough for that approach, it's pretty much already been done and done well.
 
[url=http:/civis/viewtopic.php?p=26069991#p26069991:26vbvm43 said:
aliftedlorax[/url]":26vbvm43]
[url=http:/civis/viewtopic.php?p=26069963#p26069963:26vbvm43 said:
AbstractDonut[/url]":26vbvm43]
And yet one of the things they used during class was to make structures, queues, stacks, lists, out of pointers or linked lists. The more I learned about programming now I've learned that for performance a linked list will never compare to a straight array.
Well, that's just not true. Linked lists are faster at growing/shrinking than C arrays. Linked lists are also persistent data structures and can avoid most copying overhead.
Theoretically you're right, but practically he's (mostly) right.


So I guess what I'm saying Objects seem very inefficient to me when you are making simple stuff.

You're right, but making simple stuff just isn't that interesting. Engineering is the art of managing complexity. The power of the human brain puts an upper limit on how much complexity a program can have. OO is an organizational technique which simplifies programs and allows us spend more of our complexity allowance on things that are interesting. For that reason it would be worth a performance hit - but in reality it does not necessitate any runtime overhead. Virtual methods do necessitate runtime over, but they're extra.
 

MilleniX

Ars Tribunus Angusticlavius
8,140
Subscriptor++
@ShuggyCoUk, I think you are posting more of the problem I have which OO kinda glosses over in my opinion, the lifecycle of the object. In the later languages you build and forget
[1] One of the defining characteristics of most high-level languages is that memory management is more automated than it is in C. In particular, fully garbage-collected language offer some very nice properties that are not directly expressible in C.

First, it's possible to enforce strict memory safety. In concert with strong typing, it is impossible for a pointer in a GC language to reference non-allocated memory or memory allocated to an object of a type other than its own. It's also impossible to leak memory by dropping your last reference to an allocated object. The large classes of errors that this eliminates are a boon to productivity.

Second, garbage collected languages can provide a few interesting performance benefits. A typical modern collector uses a moving/copying strategy that gathers up all live data, and thus leaves a large contiguous address range free. Within that space, allocation can be done simply by incrementing the 'free' pointer by the size of the allocation, and returning the result - as cheap as an allocation strategy can get. All objects being allocated or relocated close to things that reference them also grants a great degree of locality that consolidates itself over time. Since locality of reference is the defining feature that computer architecture is persistently tuned for, this goes a long way.

I'll close this post by noting that the nascent languages that are positioning themselves as replacements for C and C++ all move away from manual memory management. Go and D use garbage collection. Rust has a rich collection of pointer types that directly express ownership and lifetime semantics.


[1] I think you might have just conflated binary object files with language-level objects here, but I'm going to disregard that.
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
I think you are confusing quite a few concepts.

It is not concurrency that tends to make arrays faster (in fact due to the way processors arbitrate shared memory coherency in cache lines it can make them worse if done poorly) it is spatial and temporal coherency: put simply if you look at something at a[x] there's a good chance you will look at a[x plus or minus some small number] very soon afterwards. All modern processors attempt to deal with the memory/CPU bottleneck with cache, and they read in a block of memory in one go, as well as allow speculative preloading of them in an asynchronous fashion.

Linked lists do still have their uses, but most people shouldn't bother unless their data structure is heading past 5 digits in size. However hybrid data structures, which link sections of contiguous memory together often perform way better.

Also you don't "pass files around". Using wooly concepts isn't helping you.
 
[url=http:/civis/viewtopic.php?p=26070323#p26070323:2w8yqunq said:
masonk[/url]":2w8yqunq]
[url=http:/civis/viewtopic.php?p=26069991#p26069991:2w8yqunq said:
aliftedlorax[/url]":2w8yqunq]
[url=http:/civis/viewtopic.php?p=26069963#p26069963:2w8yqunq said:
AbstractDonut[/url]":2w8yqunq]
And yet one of the things they used during class was to make structures, queues, stacks, lists, out of pointers or linked lists. The more I learned about programming now I've learned that for performance a linked list will never compare to a straight array.
Well, that's just not true. Linked lists are faster at growing/shrinking than C arrays. Linked lists are also persistent data structures and can avoid most copying overhead.
Theoretically you're right, but practically he's (mostly) right.
Hmm, at least in my world, those benchmarks are practically irrelevant because they do not include the cost of locking those mutable data structures. With persistent data structures there is no such overhead for concurrent access.

A recent interview with Michael Stonebraker contains a segment where he describes how much time a conventional database management system spends on managing concurrent access -- "row-based databases spend about 90 percent of their time acquiring and releasing locks, buffer management, and other activities that could be characterized as overhead in comparison to main task of reading and writing data."
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
Hmm, at least in my world, those benchmarks are practically irrelevant because they do not include the cost of locking those mutable data structures. With persistent data structures there is no such overhead for concurrent access.

Whilst this is true not all problems can be solved by allowing some parts of the system to work on out of date or inconsistent state.

Many can though
 

HappyBunny

Ars Legatus Legionis
13,232
Subscriptor
[url=http:/civis/viewtopic.php?p=26076807#p26076807:2s2zycs0 said:
AbstractDonut[/url]":2s2zycs0]I guess my point of view is somewhat narrow. Linked lists I've found for making a game are worthless, the most efficient thing to do in my case is to figure out a good starting size[chunk] and make the array. If you do it right you don't remake the array. Making that array is faster then making a equal sized LL. Accessing the nth element randomly is much much faster, even with pointer arithmetic. Which is why I brought up concurrency, where ever my array is I'm guaranteed that if I add a size to the pointer you jump over size/item places into the array. C helps you focus on these sizes and while I wasn't talking about the cache of the processor, C would help you determine the chunk size for that I would think.

This doesn't really have anything to do with OO vs Procedural. It's about using the right data structure for your task. Linked lists vs arrays is not an OO vs procedural thing, both data structures can be (and are) implemented in both programming styles.
 

RAOF

Ars Tribunus Militum
2,733
[url=http:/civis/viewtopic.php?p=26077795#p26077795:u4ndm1hu said:
AbstractDonut[/url]":u4ndm1hu]
[url=http:/civis/viewtopic.php?p=26077527#p26077527:u4ndm1hu said:
HappyBunny[/url]":u4ndm1hu]This doesn't really have anything to do with OO vs Procedural. It's about using the right data structure for your task. Linked lists vs arrays is not an OO vs procedural thing, both data structures can be (and are) implemented in both programming styles.

You are right I was responding to other posts yet the idea is the same. You learn the higher languages and it takes things from you, such as pointers in Java. The more I program the more I see that yes pointers are a huge pain in the neck, yet a huge amount of flexibility is lost by taking pointers away in making your objects. You add OO as a default thing, and it leads to ridiculous uses like the object model of Objective C, where you have to put base types into objects. Where everything in the language has to inherit from their base object. Seems like needless complexity to me. Or virtual methods, seem needless to me. Or interfaces, seem needless to me.
The appropriate question is: does the flexibility lost by giving up pointers matter in your domain. If you're writing code for a microcontroller with 4K of RAM it's entirely possible that the flexibility you give up by going to C is too much of a loss, and you'll need to do significant coding in assembly. Equally if you're writing boring business-rules code for a modern desktop machine, what would you do with raw pointer access anyway?

A significant portion of non-trivial C code ends up being roughly object-oriented anyway, just without formal language syntax. The Linux kernel uses objects - structs with state + a bunch of function pointers - all over the place, the Mesa OpenGL implementation likewise, the Xorg X11 server. They even use poor-man's inheritance by embedding a ‘superclass’ object as the first element of the derived class's struct.

[url=http:/civis/viewtopic.php?p=26077795#p26077795:u4ndm1hu said:
AbstractDonut[/url]":u4ndm1hu]
There is all these people that seem to get carried away when they learn about objects, do you really need to have 10 levels of inheritance? I guess my title isn't that great. I guess I feel the higher C languages don't give you a good sense of context of when you'd actually use objects.
Having 10 levels of inheritance is almost certainly a sign of crappy code.
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
re: pointers and OO it's an entirely false dichotomy you are presenting. C++ lets you use OO (heck *multiple inheritance* OO) and still has pointers. C# has OO, plus managed memory but also has pointers if you really want them (but you have to be aware of their limitations within a managed memory environment - you should definitely stear clear of that)

It's important to disambiguate between specific languages/families of languages rather than whatever specific language is bugging you.
 

jbode

Ars Legatus Legionis
11,752
Subscriptor
[url=http:/civis/viewtopic.php?p=26077795#p26077795:308k46fs said:
AbstractDonut[/url]":308k46fs]do you really need to have 10 levels of inheritance?

Dear God, no. Class hierarchies should be fairly shallow, with lots of delegation. 10 levels of inheritence is a Big Red Flag about that particular design, although it depends on the domain.
 

HappyBunny

Ars Legatus Legionis
13,232
Subscriptor
[url=http:/civis/viewtopic.php?p=26077795#p26077795:360irtgp said:
AbstractDonut[/url]":360irtgp]
[url=http:/civis/viewtopic.php?p=26077527#p26077527:360irtgp said:
HappyBunny[/url]":360irtgp]This doesn't really have anything to do with OO vs Procedural. It's about using the right data structure for your task. Linked lists vs arrays is not an OO vs procedural thing, both data structures can be (and are) implemented in both programming styles.

You are right I was responding to other posts yet the idea is the same. You learn the higher languages and it takes things from you, such as pointers in Java. The more I program the more I see that yes pointers are a huge pain in the neck, yet a huge amount of flexibility is lost by taking pointers away in making your objects. You add OO as a default thing, and it leads to ridiculous uses like the object model of Objective C, where you have to put base types into objects. Where everything in the language has to inherit from their base object. Seems like needless complexity to me. Or virtual methods, seem needless to me. Or interfaces, seem needless to me.

It sounds from your earlier comments that most of your programming experience came from university classes. I would suggest that you consider the possibility that millions of developers around the world have been making use of these concepts/features for years because they are actually useful, and if you haven't found why they are useful it might be because you don't have the experience which shows why they are useful.

Notably, many of these things are most useful in keeping things organized and sensible in a large project which must be maintained over time.

I'm not trying to dismiss your opinion here, and it's certainly true that newcomers can sometimes have ideas that experienced people miss. But if you come into a trade and your first thought is that the tools used regularly by people in that trade seem useless, chances are it's you who is missing something, not them.

There is all these people that seem to get carried away when they learn about objects, do you really need to have 10 levels of inheritance?

As others mentioned, this is generally an example of bad OO design.

I guess my title isn't that great. I guess I feel the higher C languages don't give you a good sense of context of when you'd actually use objects.

I'd say it's true that the way people are taught OO often does not demonstrate the best ways to use it. That doesn't mean objects aren't a useful language feature/method of organizing code and data, though.

Going back to the array vs linked list question, I just want to mention that these days people generally prefer not to use a raw array in the C sense, because it is dangerous and error prone (allowing easy mistakes to read or write memory which doesn't belong to the array). In Java, arrays are actually objects which provide protection against such errors, but even there arrays aren't the preferred way to store such data. In C++, vectors are generally preferred, because they provide almost all the benefits of arrays but are safer, and provide nice features like automatic growth to fit new elements.

Maybe its a conspiracy theory, maybe the big companies made the higher code to control how people code. Not actually to help them code.

That's just silly, and demonstrates a lot of ignorance about how these languages and concepts developed.
 
[url=http:/civis/viewtopic.php?p=26077795#p26077795:2twq0xf0 said:
AbstractDonut[/url]":2twq0xf0]... Where everything in the language has to inherit from their base object. Seems like needless complexity to me. Or virtual methods, seem needless to me. Or interfaces, seem needless to me. ...

You've not thought about it hard enough. Those things are fucking awesome at making simple and flexible code. The generic procedural equivalents are insanely obtuse.
 

MilleniX

Ars Tribunus Angusticlavius
8,140
Subscriptor++
Suppose, in the hypothetical, that you were implementing an entire computing environment yourself, so all of this 'conspiracy' stuff is moot. You want to get it done with a minimum of effort, because you want to actually use it as soon as possible. Your starting point is assembly language.

The argument being made is that for a sufficiently large system, you'll expend less total effort building convenient high-level abstractions with the low-level starting point and then implementing everything you can with the high-level stuff, than you would using the low-level for everything.

The implementation of a word processor cares nothing for how you lay out data in the stack and heap. So why should its code speak to that explicitly, at such necessary length? You have the choice to trade flexibility that's of no (or even negative) value for convenience of positive value.
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
What kills me is that the higher languages were written with C, with the intention of restricting how you code. Which means you could very well write anything in the higher languages with C yet it would take more work.

Ahahahahaaha. Implement string reverse in c, correctly, with no bugs.
Don't just google it, actually try writing one from scratch.

This is of course being unkind to c, because it's concept of string being char* is toxic to doing simple coding against them.
 
[url=http:/civis/viewtopic.php?p=26096057#p26096057:19mnsxc4 said:
dragonlord[/url]":19mnsxc4]I remember doing that in college. It's especially fun if you say they can't use any additional variables except an indexer :)

I just tried to do this in my head, but I can't figure it out. I just want to be clear about the problem description: Are you saying that there exists a function reverse_string(char*) which returns a correctly reversed c string, whose implementation only creates a single local variable of type int? Just want to be clear about the problem description.
 
[url=http:/civis/viewtopic.php?p=26095605#p26095605:jhy500wz said:
ShuggyCoUk[/url]":jhy500wz]
What kills me is that the higher languages were written with C, with the intention of restricting how you code. Which means you could very well write anything in the higher languages with C yet it would take more work.

Ahahahahaaha. Implement string reverse in c, correctly, with no bugs.
Don't just google it, actually try writing one from scratch.

This is of course being unkind to c, because it's concept of string being char* is toxic to doing simple coding against them.

Then follow it up with one that works on unicode characters.
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
wait, are we allowed to call library functions, like strlen?

Unnecessary if you're allowed two ints, because strlen can be done with the same index variable and the (required) variable to hold the length.

Ah, unless you consider repeated calls to strlen to not result in the creation of a variable. I wouldn't consider that legit since space (even if just a register)is required to hold that value for a short while.

Consider implementing it on a stack machine, how big a stack are you allowed.
 

HappyBunny

Ars Legatus Legionis
13,232
Subscriptor
[url=http:/civis/viewtopic.php?p=26094401#p26094401:30n74fui said:
AbstractDonut[/url]":30n74fui]@ JJJ, I disagree with you I think the point of of interfaces or virtual methods is to control the people who code using them. The people who wrote the code did them more so that you could use their code within limitations then to help you write simple flexible code. Its more about convenience you can rely on their code yet it costs you. Surely any function could be written without either of them and it would be more flexible without the restrictions. Those restrictions are obfuscation, or the black box effect which is what OO design is about.

It's just really strange that you are turning this into some kind of conspiracy. Yes, modular code is in some way "limiting" the user. But those limitations come with great power.

Just like you are "limited" by only having certain sizes of drill bits or whatever, but the fact that those are standardized (and you don't have to make your own every time) is a huge boon to productivity.

What kills me is that the higher languages were written with C, with the intention of restricting how you code. Which means you could very well write anything in the higher languages with C yet it would take more work. How is that not trading flexibility for convenience? Which is why I think many of the answers here talked about that productivity gain by having the design of the higher languages.

Yes, all of these languages are equivalent in terms of what they can compute. That's irrelevant, though, because the point people are trying to get across to you is that the "flexibility" you are championing here is not actually a universal good. These languages and features are productivity tools. "Flexibility" can be good but it can also be bad. Tons of developers have adopted these various abstractions and language features because they help us be more productive.

Edit: Just as a simple example, consider something like the Collections APIs in any recent language (hell even C++). Are they limiting in some ways? Not always optimal compared to a carefully-tuned custom data structure? Sure. But it is incredibly useful to be able to just write HashSet<String> when you want a set of strings, and have it just work.
 

jbode

Ars Legatus Legionis
11,752
Subscriptor
AbstractDonut":oxr7u6cd said:
Or virtual methods, seem needless to me. Or interfaces, seem needless to me.

You haven't seen how they can be useful. Virtual methods allow you to defer implementation details, leaving your core logic clean and uncluttered. Interfaces give you a way to consistently define behavior among different, otherwise unrelated classes.

I'm currently working on an online banking platform; my piece is responsible for updating and retrieving real-time account information from the bank's server. We support about 300 individual institutions divided up among 40 different "cores" (other software vendors), where each core has a different message protocol and data format. Some are Web services (SOAP or REST), some are terminal connections (for which we had to implement screen scrapers - yuck), most use simple fixed-length or comma-delimited text messages, a few use XML. Some require us to establish a persistent connection, some allow us to use create a new connection for each message, etc.

Now, the basic application logic is the same for everybody; we get a request from our front end, translate and send it to the bank's core, receive and translate the core's response, and send the result to the front end. The details differ (by quite a bit), but the overall structure is the same.

For example, when we receive a request from the front end, we're given both the Message object a Connection object, like so:
Code:
void Server::process_client_message( Message *msg, Connection *conn )
{
  ...
  conn->send_msg( translated_message );
  ...
}

Now, we have a number of different connection types, all derived from the base Connection class - Unix connections, vanilla TCP connections, TCP connections with SSL, etc. But that's not relevant to the process_client_message method's logic; it only knows that it wants to send a message over that connection. So we use a virtual method -- send_message -- that's implemented differently for each Connection subclass. So we can call the process_client_message with different Connection types, such as

Code:
TCPConnection *myTcpConnection = new TCPConnection( host1, port1 );
SSLConnection *mySslConnection = new SSLConnection( host2, port2, cert );
UnixConnection *myUnixConnect = new UnixConnection( host3 );
...
process_client_message( msg1, myTcpConnection );
process_client_message( msg2, mySslConnection );
process_client_message( msg3, myUnixConnection );

We don't have to call a different process_client_message for each different connection type, and we don't have to add a bunch of logic to process_client_message to figure out the right send_msg method to call. We've decoupled the implementation details from the application logic. If I add a new connection type, I don't have to hack up my server code to accomodate it. I only need to implement the new send_msg method in the derived class, and presto, it will work.
 
[url=http:/civis/viewtopic.php?p=26095605#p26095605:13th8138 said:
ShuggyCoUk[/url]":13th8138]
What kills me is that the higher languages were written with C, with the intention of restricting how you code. Which means you could very well write anything in the higher languages with C yet it would take more work.

Ahahahahaaha. Implement string reverse in c, correctly, with no bugs.
Don't just google it, actually try writing one from scratch.

This is of course being unkind to c, because it's concept of string being char* is toxic to doing simple coding against them.

Why bother when things like GString exist? C's standard library sucks, but you don't have to use it.
 

HappyBunny

Ars Legatus Legionis
13,232
Subscriptor
[url=http:/civis/viewtopic.php?p=26099211#p26099211:2yhi8gi0 said:
chris_andsomenumbers[/url]":2yhi8gi0]
[url=http:/civis/viewtopic.php?p=26095605#p26095605:2yhi8gi0 said:
ShuggyCoUk[/url]":2yhi8gi0]
What kills me is that the higher languages were written with C, with the intention of restricting how you code. Which means you could very well write anything in the higher languages with C yet it would take more work.

Ahahahahaaha. Implement string reverse in c, correctly, with no bugs.
Don't just google it, actually try writing one from scratch.

This is of course being unkind to c, because it's concept of string being char* is toxic to doing simple coding against them.

Not terribly hard:

There are several serious bugs in your example, so you kind of just helped ShuggyCoUk demonstrate the point.
 

HappyBunny

Ars Legatus Legionis
13,232
Subscriptor
[url=http:/civis/viewtopic.php?p=26100521#p26100521:3kou78dz said:
Pont[/url]":3kou78dz]
char * result = malloc(sizeof(to_reverse));
OK, I haven't done C in a long, long time. But won't that malloc the size of a pointer, not the size of the string?

Yup, that's one of the bugs I was referring to in my comment :)
 
[url=http:/civis/viewtopic.php?p=26100521#p26100521:3cc4lt8n said:
Pont[/url]":3cc4lt8n]
char * result = malloc(sizeof(to_reverse));
OK, I haven't done C in a long, long time. But won't that malloc the size of a pointer, not the size of the string?

Right you are. What I get for spending 5 minutes on a pointer arithmetic problem. This is easily solved by not being lazy and using len as the size.
 
[url=http:/civis/viewtopic.php?p=26099211#p26099211:14j5t8dj said:
chris_andsomenumbers[/url]":14j5t8dj]Why bother when things like GString exist? C's standard library sucks, but you don't have to use it.

It is amazingly bad form to ninja edit your older posts to remove content that people are discussing. Removing your buggy example implementation will find you in violation of rule #8.

Embrace and learn from your mistakes.
 
Though I have to say, I'm not sure I understand how "C-strings are hard to work with" is an indictment of the "functions and structs are enough; object orientation is unnecessary mind-control" school of thought - because whether you implement reverse_string as a function or a method, the details of working with c-strings are the same. The implementation details of the method version of reverse_cstring in a hypothetical c-with-objects scenario have exactly the same sharp edges as the function version. (In C++ the terminology "non-member function" refers to a "function" and "member function" refers to what in most other languages would be called a "method". For this post I use "function" and "method" even though I will give C++ examples).

OO, as it is implemented in C++, C#, Java, Objective-C, Python, Ruby, and other class-based OO paradigms, is fundamentally a namespacing principle. I don't think anyone really knows if "OO" exists as a clearly defined mathematical abstraction separate from some of the details of the particular system. So for the rest of this little post I'm going to refer to the basics of class-based inheritance object orientation. It seems to be what you're complaining about, and it seems to be what most people mean when they refer to OO. So, in that kind object-oriented code scheme, OO is really about namespacing and information hiding. Namely, methods are namespaced by the data on which they are designed to operate, and the data on which they are designed to operate is hidden from methods which aren't designed for that data. From this single idea two advantages fall out: cleaner names for things, and code reuse. For example, consider two data structures: a c-string and a struct that represents a sequence of Unicode codepoints.

There are many useful methods which take the same logical action on both data structures. In "functions and structs" world, you have to name those functions differently to avoid namespace conflicts. Let me just make up an API for these structs:

Code:
capitalize_string(*char)
copy_string(*char)
reverse_string(*char)
strip_whitespace(*char)

capitalize_unicode_string(*unicode_str_ptr)
copy_unicode_string(*unicode_ptr)
reverse_unicode_string(*unicode_ptr)
strip_unicode_whitespace(*unicode_ptr)

1. Object orientation facilitates compiler-enforced namespacing and type-checking, reducing cognitive load.

In the hypothetical API above, these functions are namespaced by me, according to a convention I just made up. There's namespacing, but it's ad-hoc. Like a good engineer, I have imposed some order. This ad-hoc namespacing is inferior during the writing and reading phases of the code's lifecycle.

At write-time, I can only hope that my fellow programmers will follow this convention. In a real piece of software, I would have to spend time planning out our company's namespacing policy to make sure it handles our use cases, and then document that policy, and then insist that everyone who works on this code learns and conforms to the policy. Even if you already know C, you'll still have to learn our company's namespacing policy as soon as you get here, steepening the learning curve. Moreover, every time a function is added or searched-for by a developer who's writing code, there's additional overhead involved for that developer. Since the namespacing policy is not compiler-enforced, he has to think about how to name his functions.

Best of all, having a single, general-purpose namespacing convention built into the language naturally extends the type system. All of those class names are also types for the compiler. This allows the compiler to catch many classes of type errors automatically. A non-trivial side-benefit of having agreed upon your namespacing policy with the compiler is that intellisense/code-completion can be provided out of the box to assist the developer in resolving semi-qualified names.


There's a read-time overhead as well. After the code is written, the yield is uglier. Too much context is made explicit in a function littered with reverse_unicode_string. In the context of the code where those function calls appear, one of two things will be true: either I will already know that the code is operating on a unicode string, or I won't know and won't care whether the code is operating on a unicode string or a c-string. So seeing that long reverse_unicode_string(*my_string) is at best giving me redundant information leading to line noise, and at worst it's over-sharing and messing up my separation of concerns. This leads me to the second benefit of formally structuring your namespace.

2: Formally structured namespacing facilitates simultaneous code re-use and optimizations.

That's right, I'm going to show you ways in which object-oriented code is either faster or less verbose than equivalent "functions and structs" code.

Circle back to the original proposition: OO is a namespacing principle. Think of function names as URIs for the code they symbolize. Now, notice that when you switch to object orientation, you're switching from a single token with ad-hoc namespacing to a sequence of tokens. Now, instead of just the developers who read your namespacing policy, all developers in your language and the compiler understand your namespacing policy, and the compiler can make use of that policy by understanding what you mean when you vary some parts of that sequence but not others.

Let's take our unicode/c-string example again.

Suppose that, in our API, we want to expose a "reversed_copy" function which copies a string and then reverses it. The implementation for our two data types looks like:

Code:
char* reversed_copy_string(char* str) {
    char* copy = copy_string(str)
    return reverse_string(copy);
}

unicode* reversed_copy_unicode_string(unicode* str) {
    unicode* copy = copy_unicode_string(str);
    return reverse_unicode_string(copy);
}

The implementations are the same except they dispatch to different copy and reverse functions. It's no faster than the equivalent C++ object-oriented code, but there are twice as many functions and the symbols in each function are twice as long as in the C++ version.

Now, you might argue that the genericity of this function can be captured in C. It's true. You actually can capture this genericity in C by passing in function pointers to the specific versions of functions. You'll have to drop the modicum of type-safety that C affords and work on void pointers, but you technically can do it. It's something like this:

Code:
void* generic_reversed_copy(void* data, void* (*copy_func)(void*), void* (*reverse_func)(void*)) {
    void* copy = (*copy_func)(data);
   return (*reverse_func)(copy);
}

I'm not going to dwell on how nasty this code is to read and how nasty it is to pass around void pointers like this. Apparently the OP is an ubermensch who doesn't care about paltry things such as code readability and compile-time type checking. Those things are actually important for real people who write real software, but not to the ubermensch. Instead I am going to talk about a less obvious issue arising from our reliance on function pointers. This code is slower than the C++ equivalent compile-time dispatched generic code. The reason for this is that the compiler doesn't, and can't, know which bits of code those function pointers resolve to. For this reason it is unable to perform one of the most important optimizations for modern hardware: function in-lining. Instead of a nearly-guaranteed cache-hit for the inlined version of the code (as you'd get in the C++ or the verbose C versions), you have a guaranteed cache miss to follow those function pointers back to main memory.

In contrast, here's the OO version:

Code:
class AbstractStringBaseClass {
     AbstractStringBaseClass reversed_copy() {
         return this.copy().reverse();
     }
}

Not only is this shorter and type-safe, but, because you and the compiler have agreed on what code "this.copy" and "this.copy().reverse" resolve to, the compiler can inline those functions. Namely, this.copy resolves at compile time to (say) AbstractStringBaseClass.Unicode.copy or AbstractStringBaseClass.CString.copy, and this.copy().reverse resolves to AbstractStringBaseClass.Unicode.reverse or AbstractStringBaseClass.CString.reverse. You are varying the second part of the URI - the class name - but don't have to vary the last part of the URI, so you don't have to write it twice. This is only possible because of the structure you've induced on your namespace by agreeing to be "constricted" to the OO specification of your language.

Strange but true, my friend. This isn't exactly the same, but a similar principle is at work in this comparison of C++ vs C sorting. The C++ templating system which makes the standard library algorithms so fast is made possible by of C++'s type system, which as I've shown is a result of the OO principle that you're heedlessly maligning.

As a final thought, I want to point out that I've been careful not to conflate the advantages of formalizing your namespacing rules with OO. OO is one way of formalizing these rules. There are other formalizations, collectively called "type systems", and some are more general than OO. Haskell's typeclass system, for instance. But OO is still very useful.
 

sid0

Ars Tribunus Militum
2,364
[url=http:/civis/viewtopic.php?p=26103833#p26103833:1k9hhli9 said:
masonk[/url]":1k9hhli9]
1. Object orientation facilities compiler-enforced namespacing and type-checking, reducing cognitive load.
Surely this depends on context? Yes, OO (or at least objects, if not full-fledged inheritance) is great for data structures like strings or lists, but it is very easy to write an OO program that would be much simpler procedurally -- an obvious example being Hello World in Java vs Python. Objects are great when used in the right contexts and bad when used in the wrong ones. I think Python has the right idea here: objects are there when you need them, but the default way to do namespacing is via modules.
 
Status
Not open for further replies.