Is there a rule of thumb for how granular an object should be in OO programming? [closed] - class

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
I'm in school learning OO programming, and for the next few months, every assignment involves dice games and word games like jumble and hangman. Each assignment has us creating a new class for these variables; HangmanWordArray, JumbleWordArray, etc. In the interest of reusability, I want to create a class (or series of classes) that can be re-used for my assignments. I'm having a hard time visualizing what that would look like, and hope my question makes sense...
Let's assume that the class(es) will contain properties with accessors and mutators, and methods to return the various objects...a word, a letter, a die roll. Is there a rule of thumb for how to organize these classes?
Is it best to keep one object per class? Or group all the objects in a single class because they're all related as "stuff I need for assignments?" Or group by data type, so all the numeric objects are in one class and all the strings in another?
I guess I'm grappling with how a programmer, in the real world, makes decisions about how to group objects within a class or series of classes, and some of the questions and thought processes I should be using to frame this type of design scenario.

Realistically, it varies from project to project. There is no guaranteed 'right way' to group anything; it all depends on your needs. What it comes down to is manageability, meaning how easily you can read and update old code. If you can contain all your games in a single 'games' class, then there's nothing wrong with doing it. However, if your games are very complicated with many subs and variables, perhaps moving them all to their own class would be easier to manage.
That being said, there are ways to logically group items. For instance if you have a lot of solo functions that are used for manipulation (char to string, string to int, html encode/decode, etc.), you may decide to create a 'helper functions' class to hold them all. Similarly, if your application uses a database connection, you may create a class to hold and manage a shared connection as well as have methods for getting query results and executing non-queries.
Some people try to break things down to much. For example, instead of having the database core mentioned above, they might create one class to create and manage the database connection. They will create another class to then use the connection class to handle queries. Not that this method won't work, but it may become very difficult to manage when items are split up too small.
Without knowing exactly what you are doing, there's no way to tell you how to do it. If you reuse the same methods in each project, then perhaps you can place them somewhere that they can be shared. The best way I found to figuring out what works best is just to try it out and see how it responds!

What I see people doing is breaking down their objects and methods until each method is just a handful of code; if any method exceeds a page of code, they will try to break down the object structure further in order to shorten things up.
I personally have no objection to long methods, as long as they are readable. I think a "one-page limit" tends to create too much granularity, and risks more confusion rather than less. But this seems to be the current fashion.
Just reporting what I'm seeing in the wild.

Related

Improving Search Algorithem using Regex in CoreData? [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 1 year ago.
Improve this question
I'm transitioning from a SQLite implementation to CoreData.
In SQLite, searches are fairly limited. In a typical search, for a string like "card", I would want to know if any members of a set of letters like [n,l,j,x], would be a valid part of a word, or a whole word, in a stored dictionary of strings.
So, in the example above, I would have to look for "nard","lard","jard","xard" and then repeat that process for each subsequent position in the string: "cnrd","clrd","cjrd","cxrd".
This is slightly controlled by the fact that I only need a single match per position in the target string to "qualify" it, so I can search for "nard","cnrd","cand","carn", and if I get a match at any point, I can mark that point in the target word as qualified, and focus on the other targets.
Thus, if I got a match at "nard" and no other matches, the next loop might check "clrd","cald","carl", and so on. If I got matches at "nard","cand", the next loop would be "clrd","carl" : you get the idea.
Does CoreData, which I know under the hood is just SQLite anyway, offer any more advanced features that would allow me to improve the default algorithms I've used, perhaps using regex? Can a pattern like \^{3}[nljx]\ be somehow used?
I'm not at the point where I'm writing the code to experiment in this direction, so anything people can point me to is great.
When you use a SQLite store with Core Data, predicates are translated into SQLite code and executed in SQLite. Predicates therefore have SQLite's limits on what's possible. Core Data can use other store types with different capabilities and limitations-- for example, you can use a predicate that's any arbitrary block of code, but the entire persistent store gets loaded into memory all the time. Whether one of those would work for you depends on how much data you have.
Yes, you can use a predicate with NSMatchesPredicateOperatorType to do regex searching. SQLite doesn't support regexes directly, but Core Data registers a custom NSCoreDataMatches function to do the work without bringing everything into memory.

Modelising a blackjack table with (functional) Scala [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 6 years ago.
Improve this question
I would like to make blackjack game as a way to train my scala skills, and I would like to do so in a functional way, that is only using val attributes.
I have a table, which contains a shoe, which itself contains a list of cards.
Once I deal a card, I have to rebuild a new card list without the card, as it is not mutable, but then I have to rebuild a new shoe with the new list of cards, as the shoe is not mutable. But then I have to rebuild the table with the new shoe, as the table itself is not mutable, etc...
I feel that I am doing this wrong. What is the table is itself part of a gaming floor which is itself part of a casino, etc .. do I really need to rebuild everything every time a card is dealt, or a bet is made or a player joins or leave ?
Could someone give me some insight on the best way to design this?
Maybe should I store the state of the game in a database instead of in objects?
I have 3 suggestions,
The first is to read the book "Functional Programming in Scala" it has a chapter that covers functional state which would be invaluable in looking at this.
The second is to look at the State Monad, it is a monad which wraps a function from S => (A,S) basically a function which takes a current state as input, produces a result and a new state as output.
The last is to look at Functional Lenses, there are several implementations but they allow you to create a copy of an immutable structure with a changed value for a deeply nested attribute. I personally use the lens implementation in Shapeless
One last note, often functional programs are built such that at the outer most layer you deal with mutability and side effects, things like IO, Database interactions, etc. Your idea of storing state in a database would fundamentally mean that you are using mutable state.
In Clojure (or whatever other (semi-)functional language) I would normally solve this using one atom which is a mutable storage location which itself holds an immutable data structure which represents the entire game state. The game state will usually be modeled using an immutable hashmap with various entries. In Scala that would be a case class probably. There is nothing wrong with having mutation in a functional program, as long as it is isolated in one place and the updates are done atomically with a function that maps the previous to the next state. You'll find the same idea in many of the React implementations, like Redux which represents the entire UI as one data structure. I have no idea if Scala has something like Clojure's atom and if that is considered idiomatic.
Instead of a mutable reference you can use recursion. Every time a player has played you will enter a new recursion with the new game state.

Swift - Set vs Array [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
On one hand I want an ordered collection, on the other hand I want every item in the collection to appear only once.
I can either use an array and sort it every time I insert an item - and insert only if not in the array.
or use a Set data structure and sort it every time i query the data
Does someone have better solution?
There are several third-party libraries implementing an ordered set in Swift, so you could check them out.
Also, you could write your own implementation of an ordered set (you can base it on an existing one) if it is not an overkill for your task. The way you choose really depends on your app.
And in the end, you could use one of two ways that you proposed: using a built-in array or a set. In order to choose between them, take a look at your app: what action will be performed more often? Getting an access to elements in order (use array then) or addition/deletion of existing elements (probably, the set is the way to go).
This part was edited based on comments below
If you go for an array, note, that a built-in contains for arrays will not know that an array is sorted, so it will probably be O(N), not O(log(N)). So you should either write a custom replacement for the contains method, or (this is, once again probably a better way), write a custom collection class that implements contains the right way (however, since contains is a protocol extension method of SequenceType, my knowledge of Swift, I'm afraid, is not good enough yet to tell you how to do it properly, maybe someone else will).
UPDATE (based on your comment to your question):
I believe, in your particular case (a chat app) array is superior. You only have to sort old messages once, and you will not probably try to add very old messages once again, you only have to make sure you don't add new messages twice (it is implementation-dependent though, so you know better, I'm just assuming). So you only have to check that the last messages in your old array do not overlap with first messages in the array that you add. Sort of :)

Core Data Structure - avoiding circular reference?

I just wanted to validate my data structure.
It seems a bit convoluted to me, maybe it can be simplified?
Questions are grouped into chapters.
For each question, only one answer per session is possible.
The purpose is to be able to compare / analyze answers to the same questions (by different users or by the same users at different times, i.e. with different sessions).
A template, being a collection of chapters & questions, should not have to be replicated, if chapters and questions are the same.
(That would be necessary if Answer did not have a relationship to Session.)
Is the relationship from Answer back to Session the right strategy?
What else would you improve to simplify the model?
Thank you!
EDIT
Follow-up clarification:
The Answer is not static (e.g. "right" answer, "solution"), but some text the user inputs. It is more like a "questionnaire" than a "quiz". The answer has quantitative attributes that can be analyzed.
As stated, one question can have only one answer within a session. Because questions can indirectly belong to more than one session (via (NSSet*) question.chapter.template.sessions), they could have more than one answers and thus need a to-many relationship.
The typical scenario: User starts a new session with a certain template and fills out the answers. Then he can look at the analysis of the results and compare those with the results of other sessions that use the same template.
EDIT 2
The snapshot of the data model including attributes
honestly, this is what I would do instead of your structure, but I don't know what the purpose of the each entity because I'm not able to find out from their simple names.
this is just an idea to resolve the loop.
you can still reach all templates and all answers from the session, not directly but it does not make your life much harder.
UPDATE:
at the first and second sight, for me, it seems the Session entity is just an extra entity only here. honestly you would not need it, if you concatenate with the Template (aka Questionnaire) entity.
you have to add a many-to-many relationship between the Template and User (you can do it, don't worry about it). using this way, from each template you can reach all answers as well, and you won't have any loop.
Despite the really helpful effort by the part of #holex - the best way still seems to be to stick with my design. The simplifications I had hoped for have not materialized.

Unit Conversion Library - Objective C [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this question
Does anyone know of a good unit conversion library that works with Objective-C? Part of a small app that I'm working on requires me to take two items that are for sale and compare their prices. This means that I'll have to convert the quantities to a base unit for a valid comparison.
For example, if I have one item that can be purchased for $1 per pint and another that costs $3 per gallon, I need to be able to convert these to a common base unit.
Rather than re-invent the wheel, is there a library out there that can do the base-unit conversion for me?
Thanks!
I've just pushed my Objective-C unit conversion library to GitHub: https://github.com/HiveHicks/HHUnitConverter. Take a look at HHUnitConverter-MacOSX-Example for examples on how to use it.
The main purpose of a programming library is to abstract away general purpose, reusable code, into a higher level unit where you won't have to care about the details. But this is an area where details probably matter to your project.
Doing math for unit conversions involves a lot of trade-offs between accuracy and performance. If you use native floating point types, you need to avoid situations where a Very Large Number is added to a very small number: the small number may completely vanish. If you use a custom numerical representation, math will be an order of magnitude slower, which may or may not be a problem depending on how much math your application is doing.
Also, choosing that "common base unit" for comparisons is 1,000 times easier if you know what context you are working in. Given your example, it seems like pints or ounces or gallons or even liters might make sense. But if you were working with megaliters, a library that converted everything down to liters might lose a lot of precision. The library would either need to choose a default and be less generic, or allow changing the common unit, which would make it much more complicated (and therefore bug prone).
So, while I can't authoritatively answer your question and say no such library exists, that's why I think you haven't found one.
If you have a small number of conversions, you are best rolling your own. Instead of converting to base unit and back, you could have the direct conversion factors (pints->gallons, instead of pints->liters->gallons)
If you can bridge to python, there are many libraries available. Unum and PhysicalQuantities are two.
You could also have google do the work if you have internet connectivity, although there is probably a max limit on queries.
MKUnits is what you look for. This library is very popular among iOS developers. It is available on CocoaPods.
It provides units of measurement of physical quantities and simplifies manipulation of them. Unit conversion is very precise and straightforward process. You can easily extend it by adding your own units in no time.
I wrote an Objective-c units of measure library called UnitsKit. It does more than your basic conversion, for example it handles multiplication of units. Check it out.