Functions without arguments - what is their role in software design? [closed] - oop

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.

Related

Why did kotlin drop the "new" keyword? [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 did kotlin drop the new keyword ?
It makes it harder to see the difference between a function call and an object allocation.
The Kotlin Coding Conventions clearly state that:
use of camelCase for names (and avoid underscore in names)
types start with upper case
methods and properties start with lower case
If you follow the above and treat constructor as regular function that can be called i.e. val invoice = Invoice() the new keyword becomes redundant.
Once you accommodate yourself with the convention it's clear what a code is doing.
In fact even in Java code you'll have many implicit allocations that happen just beneath a method call like Collections.singleton(o) or Guava's Lists.newArrayList() so I don't think your argument about allocation visibility being better with the new keyword is fully valid.
(IMO) It was done because there is NO real difference between functions and object construction, i.e. nothing prevents a function to allocate an object (and they often do).
A good example is factory functions. These functions create new objects, but they are in no way class constructors.
AFAIK, the new keyword was created because of a negative experience with C\C++, where functions, returning new objects, have to be specially marked (by name conventions) in order not to forget to (manually) free the memory. In a auto-memory-managing language like Java\Kotlin it is not a concern.
Several other languages have no new keyword (Python, Scala, maybe Ceylon) and people who have switched to those languages never seem to miss it. I know I dont.

NSInteger vs int vs object [closed]

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.

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).

Is it good practice to use plurality to name collections? [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this question
Simply put, is it a good idea to name collections and composite objects using plurality?
class PandaBears {
PandaBear[] bears;
class PandaBear {
}
}
My concern is that the class names are quite similar. On the other hand, PandaBearList reveals the implementation, but is more easily distinguishable.
I would prefer PandaBearCollection. A class name that is a countable noun just agrees better with the fundamental metaphor of OOP, an "object".
For example, try describing the signature of the following two functions:
void func(PandaBearCollection collection1, PandaBearCollection collection2);
void func(PandaBears pandaBears1, PandaBears pandaBears2);
The first one would naturally be: "A function that takes two collections of panda bears".
What would be the second one? "A function that takes two panda bears"? No, it just doesn't work.
I would avoid plurality.
If you don't want to include the suffix List, you could always use the suffix Collection which is a standard convention and does not reveal the implementation details. Of course this depends on the language you are using.
There is also a C#-specific work-around which I like to use if the structure is not very complex. You can avoid creating the Collection class at all, by declaring all the methods as extension methods of the related IEnumerable<T>. So, in this case, you could declare extension methods on IEnumerable<PandaBear>, provided that your collection does not have other private variables.
I prefer using plurality because as you mention it does not indicate the implementation, which could easily change in the future. Another consideration on the naming convention is if you are using an ORM and what type of convention will it use when translating your database schema, as discussed here. You will probably get a lot of advice both ways. I think what is more important is that you pick a convention that works for you and your team and you stick with it.

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.