categories vs utility classes in iOS [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 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.)

Related

Best practice to define the helper functions in swift [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 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.

How store business logic into database?

I'd like to allow users to define simple business logic such as:
if (x and y) then ...
if (z or w) then ...
Let me put it concretely:
I'm developing a HR module that answers if applicants fulfill some requirements, to be defined by users.
Such requirements can be defined around logical operators:
(Must be 18 years old) or (under 18 years and must have parents permission)
Is putting this kind of logic inside the database ok? I think it is, but I'm afraid of spending time on this and find that its a poor approach.
It's ok. It is flexible approach, although time consuming in development.
Furthermore, you don't have to create your own DSL, it's already done, e.g. json-logic-ruby allows to keep complex rules in json.
As so often, the answer is "it depends" ;) Since it seems that the logic in this case is user-defined data, putting it into the database is absolutely reasonable.
But if you are looking to model the structure/AST of this input into separate business objects with their and and or control flow reflected in the database records, I would have to say that it's very likely overkill and will - apart from the initial implementation overhead - make future refactoring very hard.
A simple text field that will be evaluated at runtime is the easiest way to go as its contents can be very easily extracted and reasoned about.
Not knowing your definitive requirements, I'd suggest you take a look at Drools, a rules engine for Java, which has in its ecosystem also a rule storage backend and guided editor. Incidentally the example in your question looks a lot like it might benefit from a rules engine but unfortunately I don't have any practical experience with any of the related Ruby libraries.
Otherwise this article on the thougtbot blog - Writing a Domain Specific Language in Ruby - might be helpful in this context, too.
I definitely think it's okay. Because the user is defining the business logic or rules, I'd recommended splitting the business logic form field into parts(rule: if/unless, operand1: user.age, operand2: permissions.parental operator1: and, operator2: greater_than...) and then storing each business logic object as a row in a serialized JSON column. This should make them easier to validate and less error prone as compared to a single text field where the user to enter in whatever they like.
I would suggest creating a simple table to store the logic if it is predictable.
For example:
Table: business_logics
Attributes:
opt_1: decimal
opt_2: decimal
logic_opt: integer (enum: and|or)
then_statement: string
So this is extendable when you have more logic_opt in someday, btw you can get the advantage in validation & refactoring later on! Allow users to input the free texts is so risky in your case!

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.

Design advice for file parser [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I am trying to design an edifact parser, I was planning on having one class to read the file, one class to map the data and then one other class to deal with data storage. The part where I am having a major problem is in how instances of those classes should communicate with each other. Any advice would be appreciated.
I don't see a need for the classes to communicate (pass messages) but would suggest some Strategy pattern be used.
You'll have a class to read the file and make sense of it's Syntax. For example, something which can handle whitespace and return formatted information like 'token', 'word' etc.
The class which reads and parses syntax is passed into the Semantic parser. The Semantic parser makes sense of the meaning. For example you might expect "Id, command, token, string" in that order. The Semantic parser might use a Command pattern.
The Semantic class outputs structured data, so is passed into your structure builder (builder pattern).
So your code might look like;
MyDataStructure = DataBuilder(SemanticParser(SyntaxParse(FileReader(filename))));
HTH

Resources