How to git stash from a devenv that doesn’t have it integrated

Git stash enables you to switch from one branch to another without committing changes. Still, not all environments (including Visual Studio up to 2017, at least) have it integrated.

Of course, if you’re a standard dev, the command line is your probably best friend. Still, if you prefer avoiding it for git (such as if you simply trust the UI of the devenv more than your bash skills) there is a simple alternative solution you can use.

Assuming you’re on branch1, having uncommitted changes, and you want to temporarily switch to branch2, then back, you can manage everything without git stash this way:

  • Do commit changes on local branch1, even if the code doesn’t build with your current changes; don’t worry, it’s going to be a temporary commit – you’ll eventually get rid of it, and things would go as if it never existed.
  • Do not push branch1 to any remote (to ensure the commit does remain temporary).
  • Switch to branch2, and perform all the work you want there.
  • Eventually, switch back to branch1, and soft reset the branch’s head to the commit done just before your temporary one. (In Visual Studio use View history, right click the commit shown under the temporary one, and select Reset and keep changes.)
Advertisements
Posted in Miscellaneous | Tagged , , , , , | Leave a comment

Embedding custom Cocoa views with xibs into frameworks

Ever thought of defining a custom Cocoa class (inheriting from NSView or a descendant), associate it with a xib to be able to define its UI with xCode designer, and then put everything into a framework that you could reuse internally or publish/sell it to others?

It should be easy, right? But if you would try it for the first time, you could easily find out that there a few major hassles to pass in order to get a proper solution.

(Disclaimer: I know there are many developers who don’t like to use xCode for designing UI, but I personally think that defining such UI declaratively using XML – do it manually if you don’t like the designer – is better than writing spaghetti code for it.)

Now back to our goal, we can reach it in a few technical steps:

  1. Create a Cocoa framework target in the xCode project, to host our custom view(s) (and link its binaries to the app).
  2. Add a View file (xib) to the new target folder, and define the UI for the control.
  3. Add a Cocoa class file to the same location, using the same filename as the .xib, inheriting from NSView or a descendant class. Make sure it’s marked as public, as it would be eventually accessed from outside the framework.
  4. Go back to the View, and select the newly added type as the File’s owner‘s class.
  5. Use xCode‘s assistant editor to show both the view and the class file on screen, and control-drag to define outlets for the important UI elements within the view’s class.
  6. In the view class, redefine initializers to load the view from the nib (binary resource generated from the xib file), and add it as a subview (!) of the custom view.
  7. In the app, use the custom view from the framework normally.

Note that I’ve not included too many technical details in the list of steps above because I’ve posted a fully working project on GitHub, defining a CustomView within a CustomViews.framework and you should be able to gather everything from there.

But still, I think we need to answer ourselves a few conceptual questions before accepting this as a technical solution. Specifically:

  1. Why does xCode allow/suggest creating a xib when we define a custom class inheriting from NSViewController, but not from NSView?
    • I think it’s just because xCode doesn’t want to go through the subview approach proposed above, while a controller could easily work together with a (default) view.
    • Note that even if you’d create a NSViewController with an associated xib for the UI through xCode, it would work only within the app’s module – from a framework it would give an error at loading because the xib won’t be found within the app’s main (“null”) bundle!
  2. Is it OK to actually have the view loaded from xib as a subview of the custom view?
    • It doesn’t feel like an ideal solution but technically it works and I didn’t find any caveats yet. And (in my opinion) this is better than creating all the UI internals from code alone.

Finally, a small heads-up: the solution described above could partially (or entirely) apply to developing CocoaTouch views too, but it would probably require a few more steps. Still, for iOS development you can usually find more articles on the Web already, so I haven’t prepared anything myself on that side (yet). But, to address this at least with a link – if you’re on that thread, you can check this post instead.

Posted in macOS | Tagged , , , , , | Leave a comment

“Local” git repo remote on iCloud

Disappointingly, Apple doesn’t (yet?) have cloud based git repo hosting (and it seems even xCode server which previously could have allowed teams to host repos on macOS Server doesn’t offer this anymore, either – maybe awaiting for code integration features offered by a third party company that they have recently purchased.)

Of course, teams that aren’t afraid to push code to somebody else’s server (i.e. the cloud) can use a third party service like GitHub (which supports private repos for a fee), Bitbucket (which brings private repos for free!), or even Visual Studio Team Services (e.g. if they already use it for .NET projects.) While others could simply choose to host their own git server instances (which they can get for free, even open sourced).

On the other hand, if you are a single developer and would like to use git in xCode mostly for source backup purposes and to obtain some extra local code control (for your macOS/iOS projects) rather than for sharing anything with others, you might just want a repo without a remote. That simple git initialization and then standard git commit, push, and branching are offered by xCode as built-in features.

Sure, however, you cannot stop here: what would happen with your source code database in case your Mac breaks (or anything like this)? You think: since you’d (probably) deploy your apps through Apple means (i.e. their App Stores) you’d be forced to trust them at least for delivering binaries, so why not also having remote project repos on your iCloud drive? Sure, this is still going to need “somebody else’s” server, but at least it will be one of a second – not third – party!

If you reach the same conclusion and want to have a bare git repo on iCloud, I would suggest following this post – it lists all the required steps, and it works well.

But I need to add, tough, that to have full xCode integration (at least with the current development environment version) you need to ensure these steps are not missed nor replaced (I tried that “I know better” approach myself):

  • Do create a symbolic link your iCloud drive’s local folder – or to the repos folder inside it – otherwise a space in the file path would generate issues in xCode (while plain git commands would still work in a Terminal window, either by escaping the space or by quote enclosing).
  • Do add the remote (which can be named origin – that works!) from a Terminal window, even if xCode has an Add remote feature itself (with UI), because otherwise things would break deeply (for an unknown reason, probably related to the file path not being correctly considered as an URL by xCode itself at the time of adding it).

Finally, a heads-up: if you’d ever want to live-share the remote with others you won’t be able to (unless Apple changes their iCloud sharing philosophy): currently cloud drive folders cannot be shared with others (except as zipped content actually sent to them, just like with standard files).

Posted in iOS, macOS, Swift | Tagged , , , , , , , | 1 Comment

Afraid of AI?

OK (or not OK). But (anyway) you shouldn’t be afraid of AI programming.

This post, written by one of the best young programmers I’ve ever worked with (he has just started to blog – good luck Zoli!), mentions that there is a lot of misunderstanding about what AI is at its core, and what are its conceptual limits.

The essay mentions – as possibly you would otherwise realize only if you’d go away from all advertising and do some Python yourself – that AI is not the solution for every problem, being just a practical way to get some of the things, here and there, done – and lists the advantages and disadvantages of deep learning in a very objective manner (but of course, take this with a fair dose of subjectivity from my side :-)).

Sure, to do AI programming one would better be able to understand maths and statistics, and in the future maybe also some physics (going towards quantum computing), but essentially it’s not that hard and, with reasonable time spent on learning and practicing, any programmer that would do this out of love could do AI and get paid well for it!

Posted in Development | Tagged , | 1 Comment

Asynchronously awaiting for Swift await

Async-await pattern that is now common in many modern programming languages (having been introduced by C# a few years ago) is unfortunately not yet available in Swift. While it was proposed for implementation, it has not (yet) been identified as a goal for a next major release of the language tools (5).

In these conditions, service developers that indent to allow client code to start asynchronous operations and receive notifications when results are ready (without being blocked in the meantime) may choose to simply accept completion handlers – a pattern that many frameworks, including Cocoa, use today. While not that ugly as in other programming languages, this pattern is still an ugly one from my point of view, and here below I try to explain why:

  • Although to accept a completion handler the service function you can just require a final argument of an @escaping closure type, and syntax sugaring allows the client developer to define code blocks “after” the service call itself (with just a set of extra accolades), client code supplementary needs to always use self prefix for members called inside such completion blocks, since for asynchronous work they must be @escaping, and because this (using self in code) is not necessary in the initial part of the client (outside the completion handler) all symmetry is clearly broken.
  • I read that the compiler complains about self in closures in order to force the developer think more about the reference cycles that his or her code may generate (due to capturing an owned self by default.)
  • To resolve this, developers would use “[unowned self]” entries (and sometimes other capture list items) in client completion handlers. While such an “ugly” syntax could be acceptable in your service internals, requiring it from client side seems (at least) not very nice to request. (Not all developers are as smart as you!)
  • Moreover, note that if the client code developer chooses to pass a named method instead of an anonymous function (closure block) as the completion handler when calling your function, an owned self reference is retained anyway, and the compiler won’t complain, so not everything could be solved this way!

This is some example code that I’ve prepared to illustrate the issues:

class Service {
    func doSomethingAsync(_ arg: String,
                          completion: @escaping (String) -> Void) {
        OperationQueue().addOperation {
            Thread.sleep(forTimeInterval: 1)
            completion("result(" + arg + ")")
        }
    }
    deinit {
        print("Service deinitialized")
    }
}

class Client {
    init(_ service: Service, arg: String) {
        self.service = service
        self.arg = arg
    }
    let service: Service
    let arg: String
    func doSomething() {
        print("Doing something with", arg)
        service.doSomethingAsync(arg) { [unowned self] result in
            print("Completed doing something with", self.arg)
            print("- result:", result)
        }
        Thread.sleep(forTimeInterval: 2)
    }
    deinit {
        print("Client deinitialized")
    }
}

Client(Service(), arg: "value").doSomething()

What I suggest instead of this approach is using old style delegate protocols! Just like this:

class Service {
    func doSomethingAsync(_ arg: String) {
        OperationQueue().addOperation { [unowned self] in
            Thread.sleep(forTimeInterval: 1)
            self.delegate?.somethingDidComplete(
                result: "result(" + arg + ")")
        }
    }
    weak var delegate: ServiceDelegate?
    deinit {
        print("Service deinitialized")
    }
}
protocol ServiceDelegate: class {
    func somethingDidComplete(result: String)
}

class Client: ServiceDelegate {
    init(_ service: Service, arg: String) {
        self.service = service
        self.arg = arg
        service.delegate = self
    }
    let service: Service
    let arg: String
    func doSomething() {
        print("Doing something with", arg)
        service.doSomethingAsync(arg)
        Thread.sleep(forTimeInterval: 2)
    }
    func somethingDidComplete(result: String) {
        print("Completed doing something with", arg)
        print("- result:", result)
    }
    deinit {
        print("Client deinitialized")
    }
}

Client(Service(), arg: "value").doSomething()

This way – using a delegate – life is in my opinion a lot better, especially for the client code developers, as the most difficult code has been moved into the service (where it belongs), and client objects would then only need to conform to a delegate protocol to receive notifications when completion occurs; people won’t need to think about closures and retained self references, nor forcibly using self in the completion handler anymore.

Even overall (when both service and client are developed by the same team and/or if there are many delegate protocols to conform to), I think this looks a little better and functions with names instead of simple closures are always more readable and possibly, easier to maintain.

Finally, note that if you use the full delegate pattern instead of closures, it would be easy to adapt your code further to support multiple listeners on asynchronous operations’ events if ever needed (although it’s difficult to imagine a use case for that), or at least to add more functions in the delegate protocol to make your flow richer.

But before closing this article, I must say that there is a drawback or cost to pay if we do it like I suggested. That is sharing the state: reusing values optionally computed before calling the asynchronous operation in the completion handler. With closures, we get this as a built-in feature:

class Client {
    ...
    func doSomething() {
        let x = "Woo hoo"
        ...
        service.doSomethingAsync(arg) { [unowned self] result in
            ...
            print(x)
        }
        ...
    }
    ...
}

But with the delegate protocol we only have two uglier options:

  • Share the state within the client object itself; easier to maintain, but not good if you want to be able to use a single client instance and call the same type of asynchronous operation (or operations that share state) multiple times, in parallel; or
  • Update the service to pass the state upon calling the asynchronous operation, and its delegate to offer it back upon completion; this is ugly because the service needs to take care of anything further – something that it shouldn’t be concerned with – but at least it could work in all scenarios.

Of course, there’s never a single solution that could resolve all problems. I personally feel, however, that the second workaround (preserving the state through the service, like in oldest C# versions’ IAsyncCallback/IAsyncResult) could be the best way to handle things until the real async-await support will arrive:

class Service {
    func doSomethingAsync(_ arg: String, state: Any?) {
        OperationQueue().addOperation { [unowned self] in
            Thread.sleep(forTimeInterval: 1)
            self.delegate?.somethingDidComplete(
                result: "result(" + arg + ")", state)
        }
    }
    ...
}

protocol ServiceDelegate: class {
    func somethingDidComplete(result: String, _ state: Any?)
}

class Client: ServiceDelegate {
    ...
    func doSomething() {
        let x = "Woo hoo"
        ...
        service.doSomethingAsync(arg, state: x)
        ...
    }
    func somethingDidComplete(result: String, _ state: Any?) {
        ...
        let x = state as! String
        print(x)
    }
    ...
}

Update: Struggling to get a better solution, I found a possible way to continue writing completion handlers without referring self inside the code: we could use a custom capture list and actually extracting constant values for all the needed context variables, as they were at the time of initiating the asynchronous operation. I must admit that in many cases this could be easier than handling things with delegates, and would make completion handlers closer to awaited calls that are not yet available as first class citizens in the programming language. However, a remaining problem can be that the capture list may become very, very long and (therefore) somewhat ugly (and again not nice to be requested from fellow client code developers). And this won’t work if you need to also update self upon completion of the asynchronous operation:

let arg1: String
let arg2: String
func doSomething() {
    let x = "Woo hoo"
    print("Doing something with", arg1, arg2)
    service.doSomethingAsync(arg1, arg2) { [arg1, arg2] result in
        print("Completed doing something with", arg1, arg2)
        print("- result:", result)
        print(x)
    }
}
Posted in Swift | Tagged , , , , , | Leave a comment

How to improve your good code further

(Follow-up for my previous post on how to write good code from scratch.)

No, I won’t ask here to always write unit and automated UI tests, although they would also help tremendously at the time our code would be stable enough.

And I can’t ask anyone to show and explain code to somebody else either, although it would be a brilliant idea: I’m sure you do remember a few times when you spotted really strange issues in your code while simply explaining it to (silent) colleagues, but I also know that most of our peers are always busy and probably can rarely help that way.

Finally, let’s also exclude the rubber duck and any other awkward peer impersonations: code matters, but come on, never that much!

Yes, another real pair of eyes could surely help, and I’m not against team-level code reviewing techniques that our organization may have already adopted. But I think that peer reviewing alone is not the full solution towards what we really want here.

Instead (or before requesting a review), I suggest to just carefully browse that code, and add detailed inline comments to it.

As if they were to be read by an important possible customer, that asked for automatically extracted random code slices before initiating a big purchase we were waiting for so badly. Explaining everything with simple English, yet completely and in a consistent manner – like a (dev) pro!

You’ll be amazed to see how many things – minor or major – would be refactored during such commenting sessions: from simple variable renames to reorganizing code for consistency reasons, and from complex logic restructuring to deep algorithm optimizations.

(Yes, this does take more time than any live discussion, but it would require no other person’s presence whatsoever. And the comments we’d have added may further help years later too, when we’d just need to remember some deep details about our complicated system, or – who knows – even allow us to eventually sell that source code to a real customer if we’d ever wanted to!)

Posted in Miscellaneous | Tagged , , | Leave a comment

PWAs: are we dreaming?

TL;DR: PWAs are nice, but won’t become a unique development technology to converge to, due to performance and UX issues that are very hard to solve completely at OS level.

I read more and more on the Web nowadays about PWAs. That is, progressive Web apps. Actually, in my opinion, just Web sites that identify themselves as “apps”, which can therefore be downloaded and then run locally on client side, even offline, and optionally accessing local OS features and data, being linkable into the user’s home screen as well.

Google and Microsoft seem to be pushing the “new” development concept aggressively. Even Apple follows the trend, and although they are late, and don’t want to implement all “cache-ability” that the other two actors embraced, at least they appear to be willing to invest some resources in this area too. Then what’s this all about?

First, I must say that I know for sure the PWA concepts aren’t actually new: a few years ago – after Microsoft started to push JavaScript to Windows developers (a language that I needed to force myself to learn and love, as before I was trying to avoid it as much as possible), allowing people to write WinRT/UWP apps with Web technologies only and introduced TypeScript with full Visual Studio support as well (a language that I’ve been in love with from its first announcement) – I became convinced that we’ve finally reached the cross-platform nirvana. And I could create a JavaScript-based demo app that could run on Web, and with Cordova tools supported by Visual Studio, also on UWP and Android. (At that time I didn’t have a Mac to test iOS deployment too, but it was supported.)

I truly believed back then (and actually it is technically still true!) that JavaScript is the only way to be fully cross-platform today: virtually all contemporary OSes allow you to run WebView components within native apps, as they all have componentized browsers that run Web standards based code, loading and executing custom HTML and JavaScript sources while the app is running itself of course (and in a sandbox), offering also the possibility to communicate to the underlying native platform through the native app.

Technically, this way developers could write their core code just once, and then package it into multiple types of apps, such as supporting Windows (UWP) and macOS on desktop (or HoloLens), Android and iOS on mobile devices, or even node.js for cloud services like those required to develop Alexa voice skills, and classic Web sites targeting all browsers too, as needed. Of course, there will still be some technology adapting and packaging code to be written, but the core of the app will already be using a unique code base!

What PWAs seem to add to what we already have are just these two important things:

  • app manifest: ability to identify a Web site as an “app” so that browsers allow the end user to “install” the app and link it to their home screen, and optionally app stores may even automatically find them through crawlers and list them for better discoverability (instead of being URL-based like classic Web sites);
  • service workers: a new layer between the Web server and the client app code that provides “cache-ability” and offline support.

While these concepts allow end users to finally mix Web apps and native apps seamlessly, and developers to deploy to more targets with less platform adapting code, the big problems remain, however (besides not all OS vendors adopting the concepts above in the same way, i.e. standards are often so… interpretable, or even missing):

  • PWA’s code is going to still be pure JavaScript, which means it will still be not pre-compiled, getting lower runtime performance when compared to native apps.
  • The UI will still be run inside a WebView like framework within the host OS, simply because vendors can’t probably adapt their infrastructures to directly map DOM elements with ease and instead there will still be a browser-based adapter in between, triggering the same poor UX and further inefficency.

So in my opinion, PWAs are not going to ever be a true success unless the major OS vendors twist their cores to match the Web technologies and this means also the Web technologies must be twisted to provide support for better performance while remaining within standards boundaries.

Which essentially means a time when apps on all platforms could be written using the same, common, yet powerful programming language (such as an ECMAScript infinity, combining TypeScript, C#, Swift, and Kotlin, if you allow me to be a little sarcastic) and app infrastructure layers from all vendors to become so similar that OS cores themselves would accept full standardization – the same way as browsers do today (after a long war, though) – and this feels to me as very hard to get, given the fact that major players have different business strategies and probably none of them allows collaboration on low level software abstractions as it would be needed…

I therefore can’t help worrying that the PWA dream may actually be a nightmare instead; and I won’t follow this trend until I’d see concrete moves in the two directions indicated above. I’ll just keep an eye open and we’ll see what happens; who knows, maybe I misunderstood everything and the dream will eventually come true?… (Nah!)

Of course, PWAs, like every technology, i.e. like UWP, like Android native, like iOS native, like Xamarin, like Cordova, like Ionic, like React, like WPF, like Cocoa, like pure JavaScript, like C++, and – why not – like assembly language, all have their applications: creating some type of apps targeting one or more platforms. We just shouldn’t dream about any of them becoming able to solve everything alone.

We can instead learn more than one development framework and become technology agnostic. We’d think outside any single tool’s boundaries, accept diversity, and embrace controlled code duplication; sometimes we just can’t live without it, and it’s fine!

Posted in Miscellaneous | Tagged , | Leave a comment