Why are unnecessary instance variables a bad practice? - ruby-on-rails

I have heard several times that creating unnecessary instance variables is bad practice, but can't figure out why it is a bad practice?
What effects does it have if we use unnecessary instance variables in our application?
Any help would be appreciated, thanks in advance.

Because they are unnecessary but they will still float around in your views.
The catch is, you know that they are unnecessary so you won't care about them (even if they contain wrong data) but next developers won't know that they are unnecessary. He would think that there is some important reason that is why kartik defined them. He might go ahead and use them and may end up using wrong data.
Poor guy will have to struggle a lot to understand the reason of their existence. And when he will know then he may curse you :)

Using instance variable everywhere is not a wise thing to do. You can think of global variables (on a smaller scale) as an analogy. There are often methods that have data very specific to them. Sharing them across with all the methods of the object does not make sense, when you can directly pass them to specific methods as parameters. Also this may potentially lead to un-debuggable spaghetti code.

If I were you I would like to think that instance variables hold the state of my objects. Therefore I would only have to use just enough instance variables for the states I need to know or use to interact with other objects.

Related

Why would I create a singleton in swift instead of just dumping functions in a file?

With swift, isn't it possible to dump functions and variables into a file instead of implementing a singleton? Is there a good reason (like memory management or something) that I am missing, other than style concerns?
It is very much possible to do so. Module level private variables could be used as private variables for singleton class.
For me it is rather a choice dictated by what makes more sense as a solution to the problem. The language has given us tools each with its particular usage, so use them the way they are meant to be used.
If your solution requires an object with data, state and related functionality which could have only one instance then it is better to use a singleton. This will make more sense when you or someone else will try to understand code at later time.
If your solution is just bunch of loosely related functions without data or state then it is better to use functions in a file.
With swift, isn't it possible to dump functions and variables into a file instead of implementing a singleton?
Yes, it is definitely possible. However, the same is possible in Objective-C, with the same pluses and minuses.
Is there a good reason (like memory management or something) that I am missing, other than style concerns?
Two considerations are relevant here:
You can make your singleton polymorphic, expose an interface, define several implementations, and pick the specific one at runtime
You can "reset" your singleton by discarding the instance and creating a new one.
If you need concurrency, having a singleton makes it a little easier to implement.

Data Accessor object singleton or some other pattern? (Objective C)

It seems to satisfy the three requirements here: On Design Patterns: When to use the Singleton?
I need it to exist only once.
I need to access it from all over the source base.
It handles concurrent access, i.e. Locks for writes, but can handle concurrent reads.
Hi all,
I've been reading a lot of no doubt intelligent educated and wise gems of advice that Singletons are 'Evil' and singletons are anti patterns or just plain bad news.
With the argument that logging makes sense but not much else.
Just interested to know if the case of essentially a persistent data store context makes sense for a singleton, i.e. Reading/Writing from disk to memory and referencing an object graph.
And if not, how do people normally tackle this issue, I don't currently have any problem with it, I know it's created only once, it's fast and the accessor logic is in one place. Meaning it takes me one line of code to do anything data model related.
Which leaves the only argument that it's bad for testing, in that it's a hard coded production implementation to data, but couldn't I just write a method swizzle through a category or in the test code to create the test version of the singleton?
And the final argument from DI testers, is that it is a hard coded implementation, rather than simply an interface to something, which I do get but I don't really have a major drive to use a DI framework given that I can use protocols for implementation, and use separate init methods for setting up an objects state in testing. There's only ever going to be two types of state for the singleton, or realistically one type...production.
Making it (in my opinion) much easier to read and faster to develop.
Change my view SO?
Yup, for some singletons are Evil. For the new developers who has little MRC knowledge and more ARC it sounds scary because they need to mess with memory,volatile,synchronize etc.
However it is not against to use them, they indeed has their own purpose to use with some are below.
when sharing large data models like arrays and dictionaries etc between multiple screens (VC's) we can't prefer storing them in UserDefaults (because userdefaults is permanent storage and storing such large entries make app start lazily) instead singletons are best since they stay only current app context and restarting app creates new one.
when we need a stable db connection to be accessible allover the app without messing up with connecting and closing in every business classes we can go for it.
when we wanted an ability to app for theming itself dynamically we would need to create a singleton class which holds all the color,image instances etc. and use that instance in application VC/Views etc so no code duplication and re-processing theme occurs in all places.
You dont have to change your view but tweak it a bit to get some positive intention towards singletons.
Hoping this clears it out, thanks

Using yml as a data reference. Bad idea?

I need about 1,000 words to be able to be accessed constantly by my app. The reason I want it detached is so that down the line, I can dynamically change what those 1,000 words will be.
But I don't necessarily feel this requires a database injection. I feel a simple .yml file could work.
Is this a good practice? And if it is, what would be the best way to do this?
Is it ok to load the 1,000 words in a before_filter call ?
Don't think that architecturally this is the right call.
If those are to be changed rarely, then you can put them inside a constants class. If you plan to change them often, what you will do is write to file system and read from it which is exactly what every database does, but in a much much faster and optimal way then you could possibly write.
My two cents. Let us know how it worked out.
Do not use relational database unless you really need to. If your "words" are relatively immutable, can be accessed simultaneously without multithreadig concerns, you do not need querying etc - they are better off in some hash loaded for entire applications on startup
loading them for every reuest is not a good idea.
( this advice is not related to ROR )

Help me with my architecture - global variables in Ruby on Rails

I'm thinking about global variables in my rails application. I've searched the net about that, and found it (of course) flagged as a bad practice. I already knew that.
But I have not found another way than a global variable for what I need. Can an experienced Rails programmer help me ?
What I want to do is to create a new dedicated logger, for example logging to "log/audit.txt" and share it between several controllers. Of course, I would rather not have to recreate this "logger" object for every request.
For now, I create a logger in a global variable $my_logger in an initializer, and use it across my controllers.
What do you think ? Is there a better way to do that ?
Thank you.
The general OO stance against using global variables and singletons of any type -- in Rails and in all other OO habitats -- is to avoid the "slippery slope" towards not doing OO design at all. Global variables are to be avoided as much as possible, but your logger is obviously a case where a Singleton of some sort makes sense. The Rails environment is an example: you only have on Rails environment per application, and it's essentially a Singleton. Or consider Notifier.deliver...
Don't worry about where to put it if it must be global. Make a Singleton object with class methods as accessors and put it in lib or anywhere you think is appropriate (making a plugin might also be appropriate, for instance). Then you just use Logger.instance.log whatever. Of course you'll have to put in safeguards to make sure that the thing gets instantiated only once.
This SO question is extremely relevant: In Ruby on Rails how can I persist objects in memory between sessions
If you use the accepted answer, you'll be able to keep the logger in memory in production mode across requests.
However, I like the second answer...
to quote:
I wouldn't worry too much about
loading and discarding objects unless
you can come up with a benchmark that
proves it's an issue. Each request
creates an extraordinary amount of
intermediate objects as a matter of
course, and these are generally
created and destroyed in a matter of
several milliseconds.
...
Benchmark first, optimize only when
required.
Create your own custom logger class and require it when applicable.
Example here:
http://ianma.wordpress.com/2009/04/08/custom-logging-in-ruby-on-rails/

Erlang: What are the pros and cons of different methods for avoiding intermediate variables?

At one point while traveling the web, I came across a great page which contrasted the clarity and terseness of different methods of doing a sequence of operations without having to make a bunch of throwaway variables, e.g., Var1, Var2, Var3. It tried list comprehensions, folds, maps, etc. For some reason, now matter what I google, I can't find it again. Anyone have any idea what I'm talking about? Or want to explore the topic anyway?
Your question doesn't make much sense.
List comprehensions, fold, and map aren't for avoiding variables (nor are they interchangeable), they're the right ways to process data depending on what you're trying to do.
This is the article you were looking for:
http://erlanganswers.com/web/mcedemo/VersionedVariables.html
It is probably more of an art than a science. In a nutshell my advice is to lean away from using throw-aways as a general habit, but equally, do not be afraid of using them intelligently and sparingly where you feel appropriate or necessary.
When you are starting to learn then by all means use throw-away variables if it helps you break things down into understandable chunks. But try to break away from that sooner rather than later, as using throw-aways may at times make your code harder to maintain and modify. On the other hand, even when you are experienced you may sometimes find that it is worth using throwaways for the same reason : keep things readable and manageable for less experienced programmers. Purists may say that you should never use them, but I believe that when you consider the lifetime costs of software maintenance it is important to remember that readability is very important. Maybe this argument doesn't apply if you are lucky enough to work in an environment that only hires the best of the best, but for the rest of us that's simply not a reflection of the real world.
The bottom line : what is "right" depends on your skill level, the skill level of your peers, what you are doing, and the likely volatility, complexity, and lifetime of the code. Use your best judgement.
In response to the answer saying the question doesn't make sense, you would certainly think it made sense if you saw the article to which I'm referring. The point is to elegantly process a series of statements without redundant intermediate variables. Zed is right on target. I really wish I could find the original link because it was super detailed and went through 5 or 6 methods, some of which were referenced from the erlang mailing list, and weighed the pros and cons of each.

Resources