NSInteger vs int vs object [closed] - objective-c

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
I'm quite new to objective-C, and as I've been learning I've been trying to make my own program.
The idea is there is a variable (or object?) named totalSave, a method addToTotalSaved with a parameter saveAmount, and multiple objects (each object would give the parameter saveAmount a different value) that when acted on will cause addToTotalSaved to be 'sent', or whatever the terminology is, to totalSave so that totalSave increases by the correct amount.
First of all, if my idea of how the code works is completely wrong could you offer a better way? ...I feel like this shouldn't be complex - but otherwise my question is what should totalSave be? An int? A NSInteger? An object?

It does sound like you've made it overly complex. Obviously, the idea is not really "there is a variable named totalSave" since the user could care less about where you store it, and from the rest of your post, you actually don't care about how you store it.
That said, in order to make this a bit more concrete, let's think about a "total score" state that numerous parts of the program might add to. There are a couple of approaches you might take. In any case, you likely have some object somewhere that is keeping track of the score. We'll call it the Game object, but it could be a Level or whatever.
So there are three big schools of thought: you can pass this Game object around to everyone, you can have a Game singleton, or you can use notifications. Each of these approaches has advantages, and any one you pick is probably fine for a simple program (personally, for a very simple program, I'd use a singleton).
In the first scheme, at some point in the program you create a Game object that has some addToScore: method. You assign this object as a property on every other object that needs to update the score. Each of those calls [self.game addToScore:value]. This approach makes unit testing a bit simpler, but can be a bit tedious to implement.
In the second scheme, you have some shared singleton +[Game sharedGame]. When you want to update the score, call [[Game sharedGame] addToScore:value]. This is generally the easiet to implement.
In the third scheme, you have some object (Game) that uses NSNotificationCenter to observe some notification. When you want to update the score, you just post a notification that includes the amount to add in its user dictionary. This is great for keeping things extremely decoupled, but again can be a little tedious in the more usual case.
But as #Chuck notes, you're probably over-thinking this, and you may want to go back and work through some of the tutorials to get a better sense of how these things usually work. The kind of situation you're describing is not very complicated.

It sounds like you want a class, containing an integer value with the total. Then you want to give that class a function addToTotal(somenum).
Conceivably you could do this all procedurally, but if you want to re-use this Total, I'd recommend stuffing it in a class.

Related

Functions without arguments - what is their role in software design? [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 4 years ago.
Improve this question
In his book "Clean Code", Robert Martin states that the ideal number of function arguments is zero. Most people will agree that too many function arguments cause lots of issues. But as far as I can see, a function with zero arguments belongs to at least one of these categories:
The function is trivial and always returns the same value.
The function lacks referential transparency, its return value depends on external mutable state.
The purpose of the function are its side effects.
Now functions of type (1) are not really useful while (2) and (3) should be avoided for well-known reasons.
I am aware that the book I mentioned is about OOP, so functions typically belong to an object and get an object reference passed as an implicit argument. But still, accessing object attributes either means (2) or (3).
So what am I missing?
If you answer this question, please don't just communicate your opinion but provide reasonable arguments or specific examples. Otherwise it will probably get closed.
So what am I missing?
The key word in Martin's statement is "ideal". If you continue reading, he writes in depth about functions with one, two, and three arguments, but only mentions niladic functions in one context - testing. He claims that they are trivial to test, presumably because there is only one possible outcome, and it's either right or wrong.
So this is an ideal, and the principle to take from it is the fewer arguments, the better. In reality, obviously, this ideal is rarely achieved. The purpose of a function is usually to take input, whether directly, or indirectly through the object or system state (note that I would call those "arguments" as well to be consistent with Martin's analysis), and provide an output. When you have multiple arguments, the number of test cases increase exponentially, the maintenance is more difficult, etc.
So you are not "missing" anything, so long as you recognize that this is an ideal goal and not something that you should take as an absolute.
Some examples of "pure" niladic functions in C#:
DateTime.MinValue
String.Empty
Niladic functions in C# that return object or system state:
DateTime.Now()
object.GetHashCode()
String.Length
The object's attributes will essentially serve as the arguments to the function. In this way, you can directly manipulate the object you are working with, rather than passing and returning values which you then attribute to the object after performing some behaviour contained in the function.

Why is public/private such an important programming aspect? [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 7 years ago.
Improve this question
Why do in most programming languages do you get the ability to have private and or public methods/functions classes and properties?
Does it make much of a difrence to let's say.. have all classes, methods and properties be public?
I know that if you have all your methods, classe ans properties set to private nothing will work.
So at least I know that much.
But does the distinction between the two matter? What's the big deal if one class knows another Class "that is meant to be private" exists?
When you make something public, you enter a contract with the user class: "Hey, this is, what I offer, use it or not." Changing the public interface is expensive, because you have to change all code using that public interface, too. Think of a developer of a framework like Cocoa used by thousands of developers. If you change one public methods, for example removing one, thousands of apps break. They have to be changed, too.
So making everything public simply means that you cannot change anything anymore. (You can, but the people will get angry at one point.)
Let's think of having a class implementing a list. There is a method to sort it: sortListWithKey. You make that public because you want the users of the class to get a sorted list. This is good.
There are several algorithms for sorting. Let's say, you implement one that needs to calculate the meridian (the middle element). You need this method internally for your sorting algorithm. So it is enough, to implement it privately. Changing the whole structure of data holding including the implemented sorting algorithm is no problem and will not break existing code using that class.
But if you made the meridian method public (remember: you implemented it, because you needed it internally), you still have to keep it, even the new sorting algorithm does not need it. You cannot remove it anymore, even with the new structure it is very hard (and/or expensive) to keep the method.
So make that part of your implementation public that is useful for the users, but no more. Otherwise you shackle yourself.
If humans had perfect memory, documentation and communication skills, and made no mistakes, then there might not be a useful difference. But using or changing something from the wrong file and then forgetting about it (or not documenting it clearly for the rest of the team, or yourself in the future) is too common a cause of hard-to-find bugs.
Marking things private makes it a bit more work to create the same types of bugs, and thus less likely that lazy/sleepy programmers will do all that extra work just to mess up the application.
In computer science it is called information hiding. You, as a programmer, want to offer only necessary methods or properties to other programmers which will use your public API and this is the way how you can achieve so-called low coupling between modules.

What are the pros and cons of creating a new class? [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 9 years ago.
Improve this question
This is a probably a very basic question, but it's one I'm actually running into as I'm learning more about Actionscript 3 in particular. However, my first question is very general: When is appropriate to put functionality in a new class rather than a new function in the same class? According to this Java tutorial, which focuses on basic object-oriented principles, a class is supposed to be a "blueprint of an object". I always understood this to mean that any functionality or behavior that the object would use should be contained within the class. However, according to the single responsibility principle, each class should have only one reason to change. For example, you should have one class to compile a report and one class to print it rather than a single Report class.
Can you guys help me understand the pros and cons to creating a new class? What are the costs to splitting an object into multiple classes? Are there compile-time or performance costs for keeping related functionality in the same class, or for splitting it into two? Are there perhaps times that you would want to split things out, while you might want to keep them together other times?
As far as I remember, there isn't a big difference between having 1 class which can do everything or several classes which can do the same.
It's about readability and how you can extend the code. It's also just about clean code and coupling.
If you have a class called "Printer" you don't want to have "WaterCoolerSound()" in it. Of course the more objects you have the higher the chance is that you can run out of memory. But I am not entirely sure whether one object with all functionality or several classes with the same functionality spread out, takes more memory.
In fact, you could say that if you JUST need a little bag to hold on to some data and not be able to dance like a bear at the same time, it would make sense to have two separate classes.
It's advisable not to think about the performance before you have the code. From the maintainability and understandability viewpoint, of course, smaller classes, with smaller methods are superior. (see The Single Responsibility Principle again :)
Don't get so confused about making classes for just a function. A class should have only related functions.If the functions are of different kinds which will do totally different functionalities and use totally different kind of variables then only u should make a separate class.

Bad practice to use 5 different method parameters? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I have two buttons that each can perform two different implementations (whether selected or not), so that's 4 possible implementations in total. After coding it all out, I noticed I had 20+ lines of code for each implementation and only 1 or 2 variables were different in each. I decided I want to clean this up and have each implementation call separate, smaller methods and pass the inconsistent variables as parameters.
I figure this is a better practice b/c I'm reusing code. However, in one of my methods I have to pass 5 different arguments implement the method with correct conditions.
Is having this many parameters in a method a bad practice?
Having many parameters is not necessary a bad thing.
There are patterns that create a class to group all the parameters into one object that may seem cleaner to you. Another alternative is to use a dictionary for with all the parameters as the single configuration parameter. Some of Apples classes does this (for example title font configuration in the navigation bar).
I personally would say that code repetition is worse than many methods calling each other and having multiple parameters.
If it allow you to remove many duplicate lines, I don't see any problem to do it this way.
If it's to remove 1 or 2 lines then it might not worth the effort.
In fact you can pass as many arguments as needed. There might be other ways to do what you what to achieve but without the code your 5 arguments seems valid at first glance.
There is no specific number of parameters that is generally "bad practice". A method should have as many parameters as it needs. That said, there are cases where having a large number of parameters may indicate that a better design might be possible. For example, there are cases where you may realize an object should be tracking some value in a member variable instead of having the value passed into its methods every time.
I think it's okay to use 5 params because some objective-c default method are also having 4 params like
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(updateConvMenu:)
notificationName:#"NSConvertersChanged"
object:converterArray];
What we can do to make it more clear is giving a better format to your code
disclaimer: I know zilch about objective c
It is difficult to say without seeing the code in question, and it completely depends on what you are doing. To say that having a method with five parameters is bad practice right off the bat is a bit presumptive, although it is certainly good practice to keep the number of method parameters as small as possible.
The fact that this method sounds like an internal 'helper' method (and not a publicly exposed component of an API) gives you more lee-way then you might otherwise have, but typically you do not want to be in a situation where a method is doing different things based on some arcane combination of parameters.
When I run into methods with uncomfortably long signatures that cannot be restructured without creating redundant code, I typically do one of the following:
wrap the offensive method with several more concise methods. You might create, as an example, a method for each of your 'implementations', with a good name indicating its purpose that accepts only the arguments needed for that purpose. It would then delegate to the internal, smellier method. The smelly method would only ever be used in your 'implementation specific' wrappers instead of being scattered throughout your code. Using the well named wrappers in its stead, developers will understand your intent without having to decipher the meaning of the parameters.
Create a Class that encapsulates the data needed by the method. If what the method does depends on the state of some system or subsystem, then encapsulate that state! I do this often with 'XXContext' type classes. Now your method can inspect and analyze this contextual data and take the appropriate actions. This is good for refactoring as well. If the method in the future needs more information to accomplish its tasks or implement new functionality, you can add this data to the argument object, instead of having to change every bit of code that uses the method. Only code that needs to make use of the changes will have to supply the the appropriate values to the contextual data.
This is one of those subjective questions that's really hard to answer definitively.
I don't mind a number of parameters in an Objective C method as it can make the API that's being called more clear (and the parameters can be nice & type safe, too).
If you can distill those many functions down to a smaller number of functions (or a "base" function which is called from all the other functions), that's probably also makes for cleaner code that's easier to follow and read. Plus if you make an update to that "base" function, the functionality change will be picked up by all the ways you call your action (that's can also be a good or bad thing, of course).

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.