Best practice to define the helper functions in swift [closed] - ios

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 5 years ago.
Improve this question
I have some helper functions like image compression function in my ios project. What is the best place to define them (considering memory)?
as static method inside a class
function inside a struct
function without any class (outside of class)

None of the approaches has any effect on memory. Code is linked into your executable regardless, and does not affect the size of your objects. You should make your decision based on what makes for the cleanest design.
Functions inside a struct sound like a bad idea unless the functions relate to the hosting struct.
Static class methods can be good for related functions that you want to group together, assuming they are related to the class that "hosts" them. That approach also has the advantage of "namespacing" your function names so you avoid naming collisions. (As others have pointed out, though, making methods class methods purely for name-spacing is probably not a good idea.)
Global functions are good for functions that really are global in scope and don't naturally fall into groups with other functions, but you need to be careful about naming them to avoid collisions.

The differences should be negligible. You should not use classes as namespaces as well.
I'm posting this answer despite there are perfectly valid answers already available. The point I would like to highlight is that you shouldn't really bother much with any kind of optimizations before you actually hit the problems. Here is a relevant quotation from Donald Knuth:
"Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%."
Although in your case there is unlikely to be any serious problems, whether you do it this way or that :)

The difference between a static function inside a class/struct/enum and a global function is solely the difference in the hoops you have to jump through at the calling site. For example:
class Foo {
static func bar() { }
}
func foo_bar() { }
// call the first
Foo.bar()
// call the second
foo_bar()
IMHO Classes are not namespaces and should not be used as namespaces. That's what namespaces are for.

Related

Performance impact of using Colon vs Dot for function declarations in large lua tables

I've developed the habit of declaring almost all of my modules' functions with a colon rather than a dot, but I don't use much OOP and almost never use "self".
It seems redundant that self gets passed as a parameter every time I call a function, especially if the tables are quite large.
Is there any performance impact with this? Is it worth changing all my function declarations to use a dot?
There's not much of a performance impact to passing a single additional table reference to a function. This is regardless of the table size, as the table doesn't get copied.
Rather than performance, this seems to be a question of programming style. It is very uncommon to use the colon-syntax for module functions, as this idiom is clearly meant to be used for actual method calls. As such, a library that uses it where it's not necessary will look very confusing to any other Lua programmer.

categories vs utility classes in iOS [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 are utility classes considered bad practice in iOS ? And categories used as a replacement instead of helper classes/utility classes. Is there any particular benefit that we get out of categories that we don't get from utility classes ?
Categories have a specific purpose. They extend functionality of a class in code that's external to the class for some reason (you don't have source for the original, you want different visibility for the category, ...).
When you say "helper" class, that sounds like delegates rather than categories...or just simple composition.
Actual utility classes -- ones that have no instances or state -- do exist where needed.
Utilities are not a bad practice in iOS. Sometimes, it makes sense to have them around if you need a central hub for useful functions with a specific common goal (i.e.: a MathUtils class for parsing doubles or ints in objective-c).
Having said that, by convention categories / extensions are considered nicer as they allow you to operate directly on the objects themselves without the need to allocate memory / instantiate other objects. For example, you can create a category on an NSNumber object to divide by a number easily, allowing you to have a language syntax that is easy to follow: i.e:
in swift:
number.divideBy(2)
or in objective-c
[number divideBy:2]
As opposed to:
let utility = UtilityClass()
utility.divideNumber(number, by:2)
Hopefully this helps convince you to start working with Categories, they are your best friends here!
One should not say that utility classes are worse at all. It depends on the task.
Maybe the reason for the statement is that developers coming from different programming languages don't know categories and simply use utility classes, even a category would do the job better. This esp. applies to utility classes, whose single purpose is to split an existing parent class into more lightweight parts. This is akin of bad, because it does not reflect the meaning of a class: If code is put into a class semantical correctly, you should not break the semantics for administrative reasons. It is a part of the class, let it be a part of the class.
There is a simple test for it: If you find yourself typing self.master (for master being the original class) very often (esp. this is the only usage of self at all) it is obvious that the utility class has no individual purpose and completely works on the original class.
But, of course, if you have a separate functionality, backed with a separate set of ivars, it might be correct to have extra classes for them. (Are they still utility classes? Maybe you should ask your Q more specific.)

C-style functions in Objective-C iOS application [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 8 years ago.
Improve this question
As many of us know - we can use C-style functions in our Objective-C iOS applications like this one, for instance:
NSString* returnTen() {
return #"Ten";
}
But when is it reasonable to use C style function instead of regular Objective-C method? Or just when in general one would use C-style functions in iOS application?
But when is it reasonable to use C style function instead of regular Objective-C method?
It's entirely reasonable to use a function instead of a class and methods whenever you want to define an operation that isn't tied to an object and its data. Doing that is sort of antithetical to the object oriented programming style, so most people would normally prefer to do things with classes when possible, but it's certainly not unreasonable to write a function here and there if it suits your purpose.
Or just when in general one would use C-style functions in iOS application?
The obvious case is when you're using a library or framework that provides functions. There are a great many of these. Some examples:
C-based system frameworks such as Core Foundation and Core Graphics
POSIX/C standard library
any 3rd party C library you happen to need
Also, consider that blocks are very similar to functions, differing mainly in that they have state associated with them. Blocks are used extensively in modern Objective-C, and in many cases they simplify API's by replacing or avoiding delegate methods and such.
There is nothing wrong about using what you call "C-Style functions" in an iOS project. Objective-C is a superset of C - so in a way, you're writing C all the time anyway.
Usually, you'd be eligible to use plain C functions when the purpose of the function is very atomic and/or when you'd like to "inline" the thing the functions does in the rest of your code. For example, you could be in need of a function that evaluates the biggest of two given integers. Because this is such a "small" thing to do and not worth the (admittedly tiny) overhead of sending a full blown Objective-C message (that behind the curtains needs to make use of objc_msgSend() in order to work), you could implement it as a small C function. So, instead of
- (int)biggerIntegerOf:(int)a and:(int)b {
return a > b ? a : b;
}
you could use
static inline int max(int a, int b) {
return a > b ? a : b;
}
By specifying "inline" you give the compiler a hint that says "At the place(s) in my code where I call the function max(), you can instead just inline its contents right in place as if I copy and pasted it there".

Linked list single class vs multiple classes

In my second term as an computer science student almost the whole term we have focused on writing linked lists in different variations(stack, queue, ...). The design of these lists always came down to this
class List<T> {
class ListElement {
T value;
ListElement next;
}
ListElement root;
}
with variations to which methods were implemented and how they worked (I have left out constructors and properties for simplicity here).
Some day I started learning scala and focusing on functional programming. This also came to the point where a linked list was written but in a different style of implementation.
class List[T]( head: T, tail: List[T])
Despite the different syntax and immutability this is in my opinion a different aproach.
And I thought to myself "Well you could have implemented lists the same way in C# or Java with one class less than the aproach you learned".
I can see why you would implement a linked list like that in a functional language where recursion is not as dangerous as in C# or Java because at least for my way of thinking a recursive implementation of all the usual methods on a linked list for this design is very intuitive.
What I do not understand is why are linked lists in C# or Java typically implemented in the first fashion when you could implement them the other way with less code but equal verbosity? (I am not talking about the implementation of lists in the libraries of the language but about the lists you typically write as a programmer to be)
The only benefit I can see with the first approach is that you can hide the implementation from the user a bit better but is this the reason and also is this worth the additional class?
I wouldn't even need to expose my implementation to the user as I could still implement my list internally different and maybe only have chosen to have a constructor like that and provide functionality to retreive the first element of the list as head and also the rest as tail.
The reasons for them to be "implemented in the first fashion" as you mentioned include
Performance.
Time and space complexity are the two most important concerns while writing algorithms or implementing data structures that support operations like search and sort. As you have mentioned, the lists created the recursive way aren't mutable! The very purpose of creating a list is attaining faster operations on that. So designers prefer the 'first fashion'.
Object orientation
While solving real world problems, the initial object oriented analysis and design (OOAD) matter a lot. With an object modelling that closely resembles the real world objects/things as much as they can, designers can achieve better solutions. The recursive approach seems to miss out this aspect
Scalability
Designers of APIs/Libraries keep scalability in mind when they draft the designs. A code written in the 'first fashion' is much more scalable, and easy to comprehend.
Other design concerns
This is not an exhaustive list of the reasons in any way. There are so many other factors and experience based learning that exist in the programming folklore, that lead to the choice of the first fashion.

Breaking public member functions into lots of private member functions

When I write a class's public member function that does several things, like..
void Level::RunLogic(...);
In that function I find myself splitting it up into several private member functions. There's no point in splitting the public member function up into several functions because you wouldn't do one thing without the other, and I don't want the user worrying about what to in what order etc. Rather, the RunLogic() function would look something like this...
void Level::RunLogic(...) {
DoFirstThing();
DoSecondThing();
DoThirdThing();
}
With the DoThing functions being private member functions. In Code Complete, Steve McConnel recommends to reduce the number of functions you have in a class, but I'd rather not just put all that code into the one function. My assumption of his true meaning is that a class shouldn't have too much functionality, but I'm just wondering what other programmers think regarding this.
In addition, I've been moving towards exposing less and less implementation details in my public member functions, and moving most of the work to small private member functions. Obviously this creates more functions...but that's where the question lies.
You are right to want to keep the public method simple, and split its functionality into multiple private methods.
McConnell is right that you should reduce the number of methods you keep in a class.
Those two goals are not really at odds. I don't think McConnell would advocate making your functions longer to reduce the number of them. Rather, you should consider pushing some of those private methods into one or more utility classes that can be used by the public class.
The best way to accomplish this will depend on the details of your code, of course.
I recommend breaking them into separate methods, where each method takes care of one small task, and have a descriptive for each private method. Breaking the methods up and the method names would make the logic code more readable! Compare:
double average(double[] numbers) {
double sum = 0;
for (double n : numbers) {
sum += n;
}
return sum / numbers.length;
}
to:
double sum(double[] numbers) {
double sum = 0;
for (double n : numbers) sum += n;
return sum;
}
double average(double[] numbers) {
return sum(numbers) / numbers.length;
}
Code Complete addresses the interface that each class exposes, not the implementation.
It may make more sense to make those smaller methods as package protected, so you can easily unit test them, instead being able to test the complicated RunLogic only.
I agree with splitting the functionality.
I've always been taught and have stuck to the knowledge that a function is defined to perform a single encapsulated task, if it seems to be doing more than one thing then it may be feasible to re-factor it. And then a class to encapsulate similar or related functions together.
Splitting these tasks down and still using a single public member in my opinion allows a class to perform that important task in the way it was intended, whilst making it easier to maintain. I also often find that there are multiple similar sections of code in the same complex method which can be re-factored into a single generic function with parameters - both improving readability and maintainability; and even reducing the amount of code.
One rule that I use is the rule of three. If I am doing the same thing three times in different places, it's worth having a separate (possibly private) member function that encapsulates that shared behavior.
The only other rule that I generally use in this situation is that of readability. If I'm looking at a member function that fills more than a full screen in my IDE, I find it hard to trace all the code paths and possible wrong turns. In that case, it's perfectly reasonable to break one monolithic member function into two or more private helper functions.
Regarding the Code Complete comment about the number of functions in a class, remember that the greatest risk involved in the number of functions is primarily linked to the complexity of the externally available interface. The more entry points you provide for other people to work with, the greater the likelihood that something will go wrong (e.g., due to a bug in one of the public members, incorrect input, etc). Adding a private member function does not increase the complexity of the public API.
You are unintentionally following the ff rules:
A class should have only one reason to change / Single responsibility principle
Which is a good thing.
By properly separating the responsibilities you are making sure that your app won't easily break due to change
I don't see the advantage of keeping especially public member functions as small as possible (measured in lines of code). Generally, long functions tend to be less readable, so in most cases, spreading the implementation of big functions improves readability, no matter whether they are part of a class or not.
As to the good advice of keeping classes as small as possible, this is especially important for the public part of the interface and for the amount of data encapsulated. The reason is that classes with lots of data members and public functions undo the advantages of data encapsulation.
A 'rule of thumb' that I use is that no one function will take more than a screen full space at a time. Although rather simple minded, it helps when you can 'take it all in' one screen at a time. It will also limit (by definition) the complexity of any one method. When you are expected to hand over your work to a co-worker for further maintenance, upgrades and bug fixes(!), keeping it simple is good. With that in mind, I agree that keeping your public methods simple is almost always the correct choice.

Resources