what does the dollar do on $height of a UITextfield object? - ios

I just got aware that there are some properties on objects of classes that have a dollar sign as prefix:
$height
$left
$origin
$size
... etc
I can use it as a setter e.g.
self.textField.$height = 44;
Q: how is this called, what is it good for and is it good practice to use is like this?

It seems that you are using category UIView+FrameAdditions.h.
More on categories here.
$ signs have no special meaning in this case - they are actually a bit unconventional to use in ObjC.
It is just a way developer named the helper methods in this category.
This $-prefix looks a bit strange but on the other hand it does help distinguish between native ObjC properties of UIView's frame and category helper methods.
Nick Farina (developer of this category) actually calls this as "kind of like jQuery for UIViews"
As for your question: is it a good practice to use it like this?
As said: $-sign is uncommon and i would ditch it personally. Especially if there is a chance that someone else will once work on the same project.
But the category itself can be very usefull and time-saving.

Related

Creating and storing generic methods in ruby on rails

I'm making a method inside a Ruby on Rails app called "print" that can take any string and converts it into a png. I've been told it's not good to make class methods for base ruby classes like String or Array or Hash, etc. so "some string to print".print is probably not something I should do.
I was thinking about making a subclass of String called Print (class Print < String) and storing it in my lib/assets folder. So it would look like: Print.new("some string to print"). So my question is, am I on the right track by 1) creating a sub-class from String and 2) storing it in lib/assets?
Any guidance would be greatly appreciated!
Answers to your question will necessarily be subjective because there are always be many answers to "where should I put functionality?", according to preference, principle, habit, customs, etc. I'll list a few and describe them, maybe add some of my personal opinions, but you'll ultimately have to choose and accept the consequences.
Note: I'll commonly refer to the common degenerate case of "losing namespacing scope" or "as bad as having global methods".
Monkeypatch/Extend String
Convenient and very "OO-message-passing" style at the cost of globally affecting all String in your application. That cost can be large because doing so breaks an implicit boundary between Ruby core and your application and it also scatters a component of "your application" in an external place. The functionality will have global scope and at worst will unintentionally interact with other things it shouldn't.
Worthy mention: Ruby has a Refinements feature that allows you to do do "scoped monkeypatching".
Worthy mention 2: Ruby also lets you includes modules into existing classes, like String.class_eval { include MyCustomization } which is slightly better because it's easier to tell a customization has been made and where it was introduced: "foo".method(:custom_method).owner will reveal it. Normal Monkeypatching will make it as if the method was defined on String itself.
Utils Module
Commonly done in all programming languages, a Util module is simply a single namespace where class methods/static methods are dumped. This is always an option to avoid the global pollution, but if Util ends up getting used everywhere anyways and it gets filled to the brim with unrelated methods, then the value of namespacing is lost. Having a method in a Util module tends to signify not enough thought was put into organizing code, since without maintenance, at it's worst, it's not much better than having global methods.
Private Method
Suppose you only need it in one class -- then it's easy to just put it into one private method. What if you need it in many classes? Should you make it a private method in a base class? If the functionality is inherent to the class, something associated with the class's identity, then Yes. Used correctly, the fact that this message exists is made invisible to components outside of that class.
However, this has the same downfall as the Rails Helper module when used incorrectly. If the next added feature requires that functionality, you'll be tempted to add the new feature to the class in order to have access to it. In this way the class's scope grows over time, eventually becoming near-global in your application.
Helper Module
Many Rails devs would suggest to put almost all of these utility methods inside rails Helper modules. Helper modules are kind of in between Utils Module and Private Method options. Helpers are included and have access to private members like Private Methods, and they suggest independence like Utils Modules (but do not guarantee it). Because of these properties, they tend to end up appearing everywhere, losing namespacing, and they end up accessing each other's private members, losing independence. This means it's more powerful, but can easily become much worse than either free-standing class/static methods or private methods.
Create a Class
If all the cases above degenerate into a "global scope", what if we forcibly create a new, smaller scope by way of a new class? The new class's purpose will be only to take data in and transform it on request on the way out. This is the common wisdom of "creating many, small classes", as small classes will have smaller scopes and will be easier to handle.
Unfortunately, taking this strategy too far will result in having too many tiny components, each of which do almost nothing useful by themselves. You avoid the ball of mud, but you end up with a chunky soup where every tiny thing is connected to every other tiny thing. It's just as complicated as having global methods all interconnected with each other, and you're not much better off.
Meta-Option: Refactor
Given the options above all have the same degenerate case, you may think there's no hope and everything will always eventually become horribly global -- Not True! It's important to understand they all degenerate in different ways.
Perhaps functionality 1, 2, 3, 4... 20 as Util methods are a complete mess, but they work cohesively as functionality A.1 ~ A.20 within the single class A. Perhaps class B is a complete mess and works better broken apart into one Util method and two private methods in class C.
Your lofty goal as an engineer will be to organize your application in a configuration that avoids all these degenerate cases for every bit of functionality in the system, making the system as a whole only as complex as necessary.
My advice
I don't have full context of your domain, and you probably won't be able to communicate that easily in a SO question anyways, so I can't be certain what'll work best for you.
However, I'll point out that it's generally easier to combine things than it is to break them apart. I generally advise starting with class/static methods. Put it in Util and move it to a better namespace later (Printer?). Perhaps in the future you'll discover many of these individual methods frequently operate on the same inputs, passing the same data back and forth between them -- this may be a good candidate for a class. This is often easier than starting off with a class or inheriting other class and trying to break functionality apart, later.

Should I override Activerecord's update() method?

I'm refactoring my Rails 5.2 app in such a way that one model (OrigM) is being split into two (OrigM, NewM). Out in the codebase, there is code that does update on OrigM objects, and I want this to now result in specialized behavior in which associated OrigM and NewM objects are updated appropriately.
It seems like a straightforward way to do this is to override update in the OrigM model, but trying to do it a simpleminded way results in infinite recursion, because apparently even the class method OrigM.update(id, new_attrs) under the hood is just finding the object with id id and calling update as an instance method on it.
I have figured out a couple other ways I could perhaps make this work, although I haven't fully tested them yet: (1) Update OrigM attributes by calling write_attribute on them individually (seems like this will not let me check validations), or (2)
self.assign_attributes(new_attrs) ## resulting in "dirty" object, then
self.save!
I'm leaning toward this second solution, as it seems like it ought to be pretty close to functionally identical to what the standard update is doing.
EDIT:
I've realized that no one can really answer this unless I am asking a question, so I will now recast it as:
QUESTION: Should I, or should I not, override AR's update method (in OrigM class)?
Commenters have said: "do not do this or you will be reviled" (which honestly I was sure someone would say lol). But... is it really such a crime? Is there a "killer" reason not to do it (something you couldn't argue with)? Or is it just a vaguely encouraged best practice?
Also: "why not just define a new method if it does something different?" Well... I guess I need to say more about the models... I don't want to try to give actual code, because it's too complex. Suffice to say: most of the code still interacts with OrigM objects, and will not know about NewM. NewM was only needed architecturally because I needed to allow multiple OrigMs to share (belong_to) a single NewM to avoid duplication of data. So I would like to allow most of the rest of the code to maintain the illusion that there is still only OrigM, and be able to update it as usual. This feels like the most elegant solution to me. If I create a new OrigM#myupdate, future developers (including myself) might curse me because they tried to do a simple update and it broke things. Iow, isn't having to know that there is a special updating function just as confusing as having to know that AR's update has been overridden?

MVC - How to create a wrapper for Html.RenderPartial?

I would like to either override or create a custom function to wrap the RenderPartial shared function found in System.Web.Mvc.Html RenderPartialExtensions.
I found an article talking about this idea here:
http://johncoder.com/Post/AdventuresinDebuggingAFriendlierCalltoRenderPartial
<% Html.TryRenderPartial("ClassB", Model.B); %>
In the example above, they have created a custom sub called TryRenderPartial that does some logic and calls RenderPartial if necessary. Unfortunately this article does not give a code example of the TryRenderPartial sub itself.
I can't figure out how to create this function because the RenderPartialExtensions is not inheritable. Also I'm not sure how to actually output the html because RenderPartial is a sub, not a function, so I don't get how to actually "return" the html. Any ideas?
It's literally trivial to wrap RenderPartial. You just create an HtmlHelper extension like so (in C#, I don't speak VB):
public static class MyRenderPartialExtensions
{
public static void MyRenderPartial(this HtmlHelper htmlHelper, string partialViewName)
{
htmlHelper.RenderPartial(partialViewName)
}
}
You would add similar methods for the other overloads you want to implement.
However, chances are, you probably don't really want to do this... most likely, what you want to do is already possible in a way that the framework exposes.
This is what's known as an XY Problem, which basically means that you have Problem X, and you have decided that you need to do Y to solve it. However, you can't figure out how to do solution Y, so you're asking how to do Y rather than asking how to do your original X problem.
The reason why XY problems are bad is because chances are, the solution you've decided you need to do is not the correct solution, and the reason you're having trouble with it is because it's not the right way to do things.
Frankly, I can't think of a good reason to wrap RenderPartial, since anything you'd do is more than likely doable in some other way.
To respond to your other comment, Html helpers don't "return" anything. That's why they're Sub's. How view rendering works is rather complex, and not a subject easily discussed in an SO answer.
HtmlHelpers don't work via inheritance, they use Extension Methods.
http://msdn.microsoft.com/en-us/library/bb384936.aspx

Using #properties for all instance variables coding standards

My coding team has chosen implement a coding standard of using #property's for all instance ivars. For publicly facing things, we of course define them in our .h files, but for our private things, we define them in the .m file in an interface above our implementation.
Does it matter if I refer to them as self.myvar = whatever or as [self setMyvar:whatever]? It doesn't seem to matter at all to me, and there seems to be a great deal of mixing one way or the other in our code base.
self.myvar = whatever
is syntactic sugar for
[self setMyvar:whatever]
They're exactly the same thing. No difference at all.
As others have indicated, foo.bar and [foo bar] are equivalent (save for the additional type requirements on the former, but that is minor).
FWIW, our team decided to eschew the dot syntax completely. The motivation is to avoid ambiguity; a message send always looks like a message send and .s are always used to access structure members.
We also limit our use of #{} and #[] to the creation of collections only. All accesses are done via indexOfObject:, objectForKey:, etc...
As well, we use ARC everywhere save for a couple of border files that sit between ObjC and C++. And we have the static analyzer turned on for all DEBUG builds and all warnings are treated as hard errors. We've also turned on just about every compiler warning that is practical (there are some that simply aren't practical to use).
There is plenty of similar questions.
In our coding standards, we don't care about using dot notation or method to access the property. We even sometimes use dot notation for methods which are not formally declared as property because with library methods it's sometimes hard to know without checking the docs and it doesn't make a difference.
It never makes sense to forbid direct method calls (hard to enforce).
I saw coding standards forbidding the dot notation.
In general I tend to prefer dot notation because it enables me to split assignments into visually separated parts, e.g.
self.a = x;
against
[self setA:x];
The second just seems less readable to me but it's a matter of personal taste.
On the other hand, sometimes it's easier to use the method directly, e.g. when you have the object as an id and you would have to cast to use the dot notation.
I think that mixing both is a good solution. Choose the one that will increase the readibility at the given place.
self.myVar = x is actually compiled to [self setMyVar: x];. There's no run-time difference.
However; for ease of code readability, I'd advise sticking with one scheme or the other. If you've already had properties enforced, it'd be better to leave everything in the dot notation - if for no other reason than because this allows your code to be more easily searched.

Is it bad design to base control flow/conditionals around an object's class?

I'm currently working on a Rails project, and have found times where it's easiest to do
if object.class == Foo
...
else if object.class == Bar
...
else
...
I started doing this in views where I needed to display different objects in different ways, but have found myself using it in other places now, such as in functions that take objects as arguments. I'm not precisely sure why, but I feel like this is not good practice.
If it's not good practice, why so?
If it's totally fine, when are times that one might want to use this specifically?
Thanks!
Not sure why that works for you at all. When you need to test whether object is instance of class Foo you should use
object.is_a? Foo
But it's not a good practice in Ruby anyway. It'd much better to use polymorphism whenever it's possible. For example, if somewhere in the code you can have object of two different classes and you need to display them differently you can define display method in both classes. After that you can call object.display and object will be displayed using method defined in the corresponding class.
Advantage of that approach is that when you need to add support for the third class or a whole bunch of new classes all you'll need to do is define display method in every one of them. But nothing will change in places where you actually using this method.
It's better to express type specific behavior using subtyping.
Let the objects know how they are displays. Create a method Display() and pass all you need from outside as parameter. Let "Foo" know to display foo and "Bar" know how to display bar.
There are many articles on replacing conditionals with polymorphism.
It’s not a good idea for several reasons. One of them is duck typing – once you start explicitly checking for object class in the code, you can no longer simply pass an instance of a different class that conforms to a similar interface as the original object. This makes proxying, mocking and other common design tricks harder. (The point can be also generalized as breaking encapsulation. It can be argued that the object’s class is an implementation detail that you as a consumer should not be interested in. Broken encapsulation ≈ tight coupling ≈ pain.)
Another reason is extensibility. When you have a giant switch over the object type and want to add one more case, you have to alter the switch code. If this code is embedded in a library, for example, the library users can’t simply extend the library’s behaviour without altering the library code. Ideally all behaviour of an object should be a part of the object itself, so that you can add new behaviour just by adding more object types.
If you need to display different objects in a different way, can’t you simply make the drawing code a part of the object?

Resources