What is meant by the term "consumable" with regards to object orientation? - oop

An interviewer used this term with me six months ago and I really didn't know what he meant. I asked him to clarify and... he didn't. I've searched the web off and on for a definition, and while I've seen it used in other questions or topics, I've never been able to find a clear, concise definition and example. So, can someone please help me and shed some light on what "consumable" means? Especially when used as in "One object is (or is not) consumable by another object." I've made some inferences from context, but I don't really know how correct I am.

Some additional context would be useful, but I suspect the relevant definition is something like accepts as a parameter.
In particular, when one speaks of a particular data format one can say that some program produces or consumes that format; this is just the generalization of that to object interfaces. Object (class) A is consumable by object B iff an A can be given a B and use it directly (as opposed to needing some kind of adapter).

I would guess he probably ask Type compatibility between one object to another and how one object can be passed (consumed) by others. Hard to answer though without the real context.

Related

Downsides about using interface as parameter and return type in OOP

This is a question independent from languages.
Conceptually, it's good to code for interfaces(contracts) instead of specific implementations. I've got no problem understanding merits about the practice.
However, when I really code in that practice, the users of my classes, from time to time need to cast the interfaces for specific needs of specific functions provided by specific classes that implement that interface.
I understand there must be something wrong, either on my side or on the user's side, as the interface should expose all methods/properties(in the case of c#) that can possibly be necessary.
The code base is huge, and the users are clients.
It won't be particularly easy to make changes on either side.
That makes me wonder some downsides about using interface as parameter and return type.
Can people please list demerits of the practice? And please, include any solution if you know how to work around it.
Thanks a lot for enlightening me.
EDIT:
To be a bit more specific:
Assume we have a class called DbInfoExtractor. It has a public method GetInfo, as follows:
public IInformation GetInfo(IInfoParam);
where IInformation is an interface implemented by specific classes like VideoInfo, AudioInfo, TextInfo, etc; IInfoParam is an interface implemented by specific classes like VidoeInfoParam, AudioInfoParam, TextInfoParam, etc;
Apparently, depending on the specific object passed into the method GetInfo, the DbInfoExtractor needs to take different actions, as it is reasonable to assume that for different types of information, the extractor considers different sets of aspects(e.g. {size, title, date} for video, {title, author} for text information, etc) as search keys and search for relevant information in different ways.
Here, I see two options to go on:
1, using if ... else ... to decide what actually to take depending on the type of the parameter the GetInfo method receives. This is certainly bad, as avoiding this situation is one the very reasons we use polymorphism.
2, We should call IInfoParam.TakeAction(), and each specific implementation of IInfoParam has its own TakeAction() method to actually search and find the corresponding information from the database.
This options seems better, but still quite bad, as it shouldn't be the parameter that takes action searching and finding the information; it should be the responsibility of DbInfoExtractor.
So how can I delegate the TakeAction back to DbInfoExtractor? (I actually wrote some code to do this, but it's neither standard nor elegant. Basically I make parameter classes nested classes in DbInfoExtractor, so that they can call various versions of TakeAction of DbInfoExtractor.)
Please enlighten me!
Thanks.
Thanks.
Why not
public IVideoInformation GetVideoInformation(VideoQuery);
public IAudioInformation GetAudioInformation(AudioQuery);
// etc.
It doesn't look like there's a need for polymorphism here.
The query types are Query Objects, if you need those. They probably don't need to be interfaces; they know nothing about the database. A simple list of parameters (maybe just ID) might be sufficient.
The question is what does the client have, and what do they want? That's your interface.
Switch statements and casting are a smell, and typically mean that you've violated the Liskov substitution principle.

Where is changing the class of an object at runtime allowed

Do you know programming languages where changing the class of an object at runtime is allowed (supported)?
Please give a short example regarding the syntax. Give a use case, if you know any. Examples involving duck typing are welcome as well, so do not shy away from mentioning these languages.
Update: I figured out that Smalltalk has changeClassTo and become. CLOS can do change-class. I found a paper suggesting to use these mechanisms to implement 'husk objects' that are referenced at runtime, but only constructed from some persistence when actually accessed, providing some nifty lazy loading of related objects.
I assume, you mean the following:
You have an object of class A. But you would like to treat it as an object of class B.
There are some constructions possible:
If B is a subclass of A you can cast the object to B (but it should be created as B else you have unexpected (and hopefully unwanted) results).
In some languages you can cast anything to anything. If you know what you are doing, this is great, else prepare for several holes in your foot.
You mention ducktyping. I have no practical experience with it. But As far as I know, duck typing is something like this: "I need an object that support methods X, Y and Z." In that case you don't care about the class. You just want it to quack, swim and walk at your command.
Give a usecase
??? I'd expect you to ask for a solution on a specific use case.
Changing type of an object? I think "No."
But if you like to change part of an objects capabilities or behaviours have a look at loosely coupling!
For example your class holds a member of type File_Saver. There's a public setter accepting any instance of File_Saver and you can inject File_Saver_XML, File_Saver_PDF, ...
It's no common way, but any processing inside a class can be done by 1-n loosely coupled handlers, which you can exchange from outside.
Melt down to your question: You need a wrapper + a setter. :-)
Coming back to the case after some time, I've come to the conclusion that you want duck typing if you feel the need of changing an objects class.

Is a class that manages multiple classes a "god object"?

Reading the wikipedia entry about God Objects, it says that a class is a god object when it knows too much or does too much.
I see the logic behind this, but if it's true, then how do you couple every different class? Don't you always use a master class for connecting window management, DB connections, etc?
The main function/method may know about the existence of the windows, databases, and other objects. It may perform over-arching tasks like introduce the model to the controller.
But that doesn't mean it manages all the little details. It probably doesn't know anything about how the database or windows are implemented.
If it did, it could be accused of being a God object.
A god object is an object that contains references, directly or indirectly, to most if not all objects within an application. As the question observes, it is almost impossible to avoid having a god object in an application. Some object must hold references to the various subsystems: UI, database, communications, business logic, etc. Note that the god object need not be application-defined. Many frameworks have built-in god objects with names like "application context", "application environment", "session", "activator", etc.
The issue is not whether a god object exists, but rather how it is used. I will illustrate with an extreme example...
Let's say that in my application I want to standardize how many decimal places of precision to show when displaying numbers. However, I want the precision to be configurable. I create a class whose responsibility is to convert numbers to strings:
class NumberFormatter {
...
String format(double value) {
int decimalPlaces = getConfiguredPrecision();
return formatDouble(value, decimalPlaces);
}
int getConfiguredPrecision() {
return /* what ??? */;
}
}
The question is, how does getConfiguredPrecision figure out what to return? One way would be to give NumberFormatter a reference to the global application context which it stores in a member field called _appContext. Then we could write:
return _appContext.getPreferenceManager().getNumericPreferences().getDecimalPlaces();
By doing this, we have just made NumberFormatter into a god object as well! Why? Because now we can (indirectly) reference virtually any object in the application through its _appContext field. Is this bad? Yes, it is.
I'm going to write a unit test for NumberFormatter. Let's set up the parameters... it needs an application context?! WTF, that has 57 methods I need to mock. Oh, it only needs the pref manager... WTF, I have to mock 14 methods! Numeric prefs!?! Screw it, the class is simple enough, I don't need to test it...
Let's say that the application context had another method, getDatabaseManager(). Last week we were using SQL, so the method returned an SQL database object. But this week, we've decided to change to a NoSQL database and the method now returns a new type. Is NumberFormatter affected by the change? Hmmm, I can't remember... yeah, it might be, I see it takes an application context in the constructor... let me open the source and take a look... nope, we're in luck: it only accesses getPreferenceManager()... now let's check the other 93 classes that take an application context as a parameter...
This same scenario occurs if a change is made to the preferences manager, or the numeric preferences object. The moral of the story is that an object should only hold references to the things that it needs to perform its job, and only those things. In the case of NumberFormatter, all it needs to know is a single integer -- the number of decimal places. It could be created directly by the application god object who knows the magic number (or the pref manager or better still, numeric prefs), without turning the formatter into a god object itself. Furthermore, any components that need to format numbers could be given a formatter instead of the god object. Wins all around.
So, to summarize, the problem is not the existence of a god object but rather the act of conferring god-like status to other objects willy-nilly.
Incidentally, the design principle that tackles this problem head-on has become known as the Law of Demeter. Or "when paying at a restaurant, give the server your money not your wallet."
In my experience this most often occurs when you're dealing with code that is the product of "Develop as you go" project management (or lack there of). When a project is not thought through and planned and object responsibilities are loose and not delegated properly. In theses scenarios you find a "god-object" being the catchall for code that doesn't have any obvious organization or delegation.
It is not the interconnectedness or coupling of the different classes that is the problem with god-objects, it's the fact that a god-object many times can accomplish most if not all responsibilities of it's derived children, and are fairly unpredictable (by anyone other than the developer) as to what their defined responsibilities are.
Simply knowing about "multiple" classes doesn't make one a God; knowing about multiple classes in order to solve a problem that should be split into several sub-problems does make one a God.
I think the focus should be on whether a problem should be split into several sub-problems, not on the number of classes a given object knows about (as you pointed out, sometimes knowing about several classes is necessary).
Gods are over-hyped.

Requesting a check in my understanding of Objective-C

I have been learning Objective-C as my first language and understand Classes, Objects, instances, methods, OOP in general, etc enough to use the language and make simple applications work, but I wanted to check on a few fundamental questions that have never been explained in examples I followed.
I think the questions are so simple that they will confuse a lot of people, but I hope it will make sense to someone out there.
(While learning Objective-C the authors are assuming I have a basic computer programming background, yet I have found that a basic computer programming background is hard to come by since everyone teaching computer programming assumes you already have one to start teaching you something else. Hence the help with the fundamentals)
Passing and Returning:
When declaring methods with parameters how is the parameter stuff actually working if the arguments being passed into the parameters can have different names then the parameter names? I hope that makes sense. I know parameter names are variables for that very reason, but...
are the arguments themselves getting mapped to a look up table or something?
Second the argument "types" (int for example) have to match the parameter return types in order for them to be passed into the method, and you always have to make your arguments values equal the parameter names somewhere else in your code listing before passing them into the method?
Is the following correct: After a method gets executed it returns a particular value (if it is not void) to the class or instances that is calling the method in the first place.
Is object oriented programming really just passing "your" Objects instance methods around with the system generated classes and methods to produce a result? If we are passing things to methods so they can do some work to them and then return something back why not do the work in the first place eliminating the need to pass anything? Theoretical question I guess? I assume the answer would be: Because that would be a crazy big tangled mess of a method with everything happening all at once, but I wanted to ask anyway.
Thank you for your time.
Variables are just places where values are stored. When you pass a variable as an argument, you aren't actually passing the variable itself — you're passing the value of the variable, which is copied into the argument. There's no mapping table or anything — it just takes the value of the variable and sticks it in the argument.
In the case of objects, the variable is a pointer to an object that exists somewhere in the program's memory space. In this case, the value of the pointer is copied just like any other variable, but it still points to the same object.
(the argument "types" … have to match the parameter return types…) It isn't technically true that the types have to be the same, though they usually should be. Some types can be automatically converted to another type. For example, a char or short will be promoted to an int if you pass them to a function or method that takes an int. There's a complicated set of rules around type conversions. One thing you usually should not do is use casts to shut up compiler warnings about incompatible types — the compiler takes that to mean, "It's OK, I know what I'm doing," even if you really don't. Also, object types cannot ever be converted this way, since the variables are just pointers and the objects themselves live somewhere else. If you assign the value of an NSString*variable to an NSArray* variable, you're just lying to the compiler about what the pointer is pointing to, not turning the string into an array.
Non-void functions and methods return a value to the place where they're called, yes.
(Is object-oriented programming…) Object-oriented programming is a way of structuring your program so that it can be conceptually described as a collection of objects sending messages to each other and doing things in response to those messages.
(why not do the work in the first place eliminating the need to pass anything) The primary problem in computer programming is writing code that humans can understand and improve later. Functions and methods allow us to break our code into manageable chunks that we can reason about. They also allow us to write code once and reuse it all over the place. If we didn't factor repeated code into functions, then we'd have to repeat the code every time it is needed, which both makes the program code much longer and introduces thousands of new opportunities for bugs to creep in. 50,000-line programs would become 500 million-line programs. Not only would the program be horrendously bug-ridden, but it would be such a huge ball of spaghetti that finding the bugs would be a Herculean task.
By the way, I think you might like Uli Kusterer's Masters of the Void. It's a programming tutorial for Mac users who don't know anything about programming.
"If we are passing things to methods so they can do some work to them and then return something back why not do the work in the first place eliminating the need to pass anything?"
In the beginning, that's how it was done.
But then smart programers noticed that they were repeating copies of some work and also running out of memory, so they decided to put that chunk of work in one central place to save memory, and then call it by passing in the data from where it was before.
They gave the locations, where the data was stuffed, names, because the programs were big enough that nobody memorized all the numerical address for every bit of data any more.
Then really really big computers finally got more 16k of memory, and the programs started to become big unmanageable messes, so they codified the practice as part of structured programming. It's now a religious tenet.
But it's still done, by compilers when the inline flag is set, and also sometimes by hand on code that has to be really really fast on some very constrained processors by programmers who know when and where to make targeted trade-offs.
A little reading on the History of Computers is quite informative about how we got to where we are today, and why we do such strange things.
All that type checks used (at most) only during compilation stage, to fix errors in code.
Actually, during execution, all variables are just a block of memory, which is sent somewhere. For example, 'id' type and 'int' are both represented as 4-byte raw value, and you can write (int)id and (id)int to convert those type one to another.
And, about parameters names - they are used by compiler only to let it know, to which memory area send some data.
That's easy explanation, actually all that stuff is complicated, but I think you'll get the main idea - during execution there are no variable names/types, everything is done via operations over memory blocks.

Object.DoSomething() vs DoSomethingWith(Object) [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
This may simply be a matter of preference, however, I am interested to know what is the best-practise way of when to use either approach.
e.g.
var person = new Person();
person.Run();
as opposed to
var person = new Person();
Excercise.Run(person);
The above example may not be the best, but my general point is when should you decide to give the object the responsibility as opposed to another class?
Don't do things for your objects. They're there to do things for you.
That sounds quite simplistic, but it's a useful maxim to follow. It means (as you've identified) calling methods on an object and it will use all the knowledge available to it to produce a result. It reinforces encapsulation and separation/containment of responsibilities
An indicator that this is not happening is code like this:
priceBond(bond.getPrincipal(), bond.getMaturity(), bond.getCoupons(), interestRate)
where the bond object is yielding all it's information to some third party. Code like the above will end up beng duplicated everywhere. Instead write
bond.priceBond(interestRate)
and keep all the information tied up in the one object.
If your objects suffer from huge numbers of getters, then it's a possible indicator that your objects aren't doing what they're supposed to.
Generally speaking, this OOPish construct:
person.Run(distance);
is just a syntactic sugar for:
Person.Run(person, distance);
where person becomes an implicit this reference. There are some subtleties with virtual functions and such, but you get the idea.
As for your question, you're basically having a rich domain model versus an anemic one, and this is a subject of a great many debates.
Normally a class, in this case Person, has behaviour;
And in this case, the behavior is Run and thus the person should have the method Run
var p = new Person();
p.Run();
The first one carries so much more conceptual clarity. A person runs, a running exercise doesn't consume a person.
The comparision is ideally not correct for few reasons:
1. Ideally each object would be responsible for it's own activities for example in case of human, human would be responsible for human.walk(), human.eat(), human.sleep() etc.
2. The parameter that is being passed to the activity is a consumed resource for that activity. It would not be wise to say Life.walk(human), as walk is not Life's activity and human is not consumable resource. Here human is the object. However it would be wise to say human.eat(food); where food is a consumable resource.
3. The sample you have given seems to potray that in second case Run is a static method and for object functioning you rarely want to implement it as a static method design.
Ideally design patterns would guide you, if implemented correctly, that which way a function will be called on an instance, but mostly what will get passed to a method is a resource that is req. to do that activity and not the action object.
I hope that clears up your doubt. For more details on design patterns you can some books by Martin fowler.
http://www.martinfowler.com/books.html
If the it's the person's responsibility to Run then i would suggest person.Run()
if Run though can handle other types of objects and it's somehow reusable outside the person object then it could stand on it's own and call it as Excercise.Run(person);
For me, i would go with person.Run();
I agree with the first answer that if the act of running is best 'understood' by the person object then that is where it should reside, for both functionality and clarity.
The second case is more suited to interpretations outside of the object and is best performed through interfaces. So instead of taking a person object the Excersize methods should take an interface, say IExcersizable that, for example, moves limbs. The Excesize.run(IExersizable) method could move one leg and then the other in quick succession. The Excesize.walk(IExersizable) could to the same but slower.
The person objec could then implement the interface to deal with the specifics of 'limb' movement.
Two situations I can see where calling an static method on an object is the preferred approach are:If there is some realistic possibility that the passed-in parameter might not support the indicated action, and such occurrence should be handled gracefully. For example, it's often useful to have a function which will dispose an object if it's non-null and iDisposable, but harmlessly do nothing otherwise;If the method does something that really isn't broadly applicable to its parameters [e.g. testing if a person has a wristwatch made by some particular manufacturer; such functionality may be used often enough to merit its own method, but likely wouldn't really belong in the Person class, nor the WatchManufacturer class].
Some people like using extension methods for the former scenario. They can sometimes help clarity, but odd rules regarding their scope can sometimes cause confusion (if I had my druthers, extension methods would use a different syntax for invocation--something like theObject..theMethod--so it would be clear when extension methods were being used and when normal methods were).
There is a slight differences:
person.Run() receives a single parameter: this
if Excercise.Run(person) is a static method, it also receives a single parameter
if Excercise is an instance, it receives two parameters: this and person
Obviously the third approach is only needed if you have to pass both parameters. I would say the first approach is better OOP and I would only chose the second one in very special circumstances (for exmaple, if Person was sealed).
I agree with Brian. Just for reference, I wanted to point out this article on "Tell, Don't Ask" and "Law of Demeter". Both are applicable here.
Pragmatic Programmer: Tell, Don't Ask
Since a Person will be doing the running, it is better to have a run method in there.
Two things:
This is not a matter of taste but has actual technical consequences. The differences between a member function and a free function have been discussed at great length already, I recommend having a look at the Effective C++ book and/or an article by Scott Meyers at
http://www.ddj.com/cpp/184401197
In short, if you make a function a member function, you'd better have a darn good reason to do so.
The readability argument should be taken with care. It depends very much on the name of the member function. Remember the SPO - Subject Predicate Object rule: there's little doubt that person.run() looks better than run(person); (at least to an english-speaking person), but what if you have other verbs than 'run'. Some verb which takes an object, for instance 'to call' in case you want to make a phone call? Compare call( person ); vs. person.call();. The former looks much nicer.