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
Swift does make a distinction between designated and convenience initializers. The documentation, however, never states why this distinction is made.
From a programmer's point of view, it seems like an extra burden: I have to think whether some initialization mechanism is "designated" or "convenience" and there are even some practical inconveniences like that I cannot call a convenience constructor of the super class which might sometimes be totally appropriate. There have to be some advantages of this concept in return. Otherwise Apple would not have introduced this feature. So what is the reason for introducing this distinction in Swift? A references to an official statements would nice.
The distinction between designated initializers and convenience initializers is not new — it's been part of the Cocoa environment for a long time. The reason for this convention is to ensure that all the internal state managed by a class is configured as intended before a subclass, or code external to the class, starts trying to use it.
Explicit initialization is one of the "safety" features of Swift. Using values before they're initialized can lead to undefined behavior (read: bugs) in C. If you declare a variable in Swift, it has to have a value. (Optionals let you fudge this a bit while still being explicit about it.) Making Cocoa's initializer chaining convention into a requirement is how Swift ensures initialization safety on top of class inheritance.
But don't take my word for it. < /LeVar> There's a great explanation of this in the series of Swift talks from WWDC — check the videos.
Totally agree on the practical inconvenience, not being able to call a convenience constructor of the super class is a total PITA...
Though I don't have any "official" answer, the conclusion I've reached is that calling a designated constructor is the only future proof way to do so.
Convenience constructors always have the possibility of being changed in future API-releases, so making the initialization of your class depend on one is highly unsafe, while the designated initializer is always going to work, no matter what changes the API is going to go through along the way...
Related
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 2 years ago.
Improve this question
How can one get a stable hash of a function at runtime?
This means the hash changes if the implementation changes, and this is recursive, so if there is a nested function call, the nested function hash will affect the outer function hash.
Not sure which language has this feature. I'm looking for a practical programming language where it is trivial and performant.
I guess functional languages, perhaps lisp or haskell are the usual suspects, but unsure how this looks like.
function myFunction() {
... // Some code, possibly using names from other files/modules/libraries
}
// Prints the hash which changes if anything in the implementation of `myFunction` changes, stable across runs.
print(hash(myFunction))
is there such a language? if so an example of how this is written and why it works is desired.
non-examples would be js, python, java...
If you want a general-purpose programming language, Unison does exactly this pervasively:
Each Unison definition is some syntax tree, and by hashing this tree in a way that incorporates the hashes of all that definition's dependencies, we obtain the Unison hash which uniquely identifies that definition.
— https://www.unisonweb.org/docs/tour
Every Unison definition is identified by a 512-bit SHA3 hash, and is immutable—you cannot modify a definition, only create a new one. Moreover, names are stored separately from definitions, so renaming is a trivial operation, and if two people write structurally the same code with only different variable & function names, their code will share the same hash and thus be identified as the same code.
As for configuration languages, Dhall does as well:
Use Dhall's support for semantic hashes to guarantee that many types of refactors are behavior-preserving
— https://dhall-lang.org/
Since Dhall is non–Turing complete, every expression has a normal form, and the hash of this normal form can be used to identify it, so when you refactor your Dhall code, you can have strong assurance that it produces identical results.
I've implemented this in a commercial application written in Common Lisp, deployed using CCL (Clozure Common Lisp).
You can do it by obtaining a represenation of the compiled image of the function using disassemble, and then hashing that using as suitable digester, like the one in Ironclad.
What I actually used in the CCL solution was the functions ccl::%function-code-words to obtain how many words there are in the function and the accessor ccl::%function-code-byte to get at the bytes (there are four times as many as the number of words).
Obviously, a hash based on the code bytes will not reflect differences in captured lexical environment between instances of functions created at the same point in the program at different times.
The implementation wasn't recursive. Rather, the overall solution iterated over a known list of functions.
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 last month.
Improve this question
I am wondering... I have read about Go some time ago and I tried to program something in it. I seems quite interesting. But I have reached handling "exceptions" in this language. I have read about their approach and it seems reasonable. I would like to know what are the advantages of the standard exceptional approach over the Go's style? What are the pros and cons?
Edit To be straight: I do not want to make any holy war about exceptions. I just wonder if this style of handling errors has any advantages? What are actual advantages of this style over standard exceptions? Is it worth wondering at all?
panic/recover is moral equivalent of try/catch exceptions. There is superficial difference (syntax) and a subtle, but important, difference of intended use.
The best explanations of problems with exceptions in general is "Cleaner, more elegant, wrong" and that's a good overview of pros/cons of exceptions vs. returning error codes.
Go designers decided that error handling by returning error codes from functions is the idiomatic Go way and the language supports multiple return values to make it syntactically easy. While panic/recover is provided, the difference is not of functionality but intended use.
Other languages exposing exceptions promote their use and in practice they are used frequently (sometimes even misused).
Go discourages the use of panic/recover. You can do it but you're only supposed to do it in very limited scenarios.
If you look at Go's own standard library, most uses of panic are for signaling fatal errors, indicating either an internal error (i.e. bug) in the library code or calling the library with wrong data (e.g. passing non-json data to json decoding functions).
But as the article you linked to points out: "The convention in the Go libraries is that even when a package uses panic internally, its external API still presents explicit error return values."
This is different from languages like C#, Java, Python or C++, where a lot of standard library code can throw exceptions to signal errors. Those languages want you to use exceptions. Go discourages the use of panic/recover.
To summarize:
idiomatic Go style is to use error codes to tell the caller about errors
use panic/recover only in rare cases:
to "crash" your program when encountering internal inconsistency indicating bugs in your code. It's basically a debugging aid.
if it dramatically simplifies error handling in your code (but if the code is to be used by others, never expose such panics to callers)
In practice the important thing is to use language's idiomatic style. In Go that's returning error codes and avoiding panic/recover. In C# that's using exceptions to signal some of the errors.
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 4 years ago.
Improve this question
Is Method Overloading considered part of polymorphism?
There are different types of polymorphism:
overloading polymorphism (also called Ad-hoc polymorphism)
overriding polymorphism
So yes it is part of polymorphism.
"Polymorphism" is just a word and doesn't have a globally agreed-upon, precise definition. You will not be enlightened by either a "yes" or a "no" answer to your question because the difference will be in the chosen definition of "polymorphism" and not in the essence of method overloading as a feature of any particular language. You can see the evidence of that in most of the other answers here, each introducing its own definition and then evaluating the language feature against it.
Strictly speaking polymorphism, from wikipedia:
is the ability of one type, A, to appear as and be used like another type, B.
So, method overloading as such is not considered part of this definition polymorphism, as the overloads are defined as part of one type.
If you are talking about inclusion polymorphism (normally thought of as overriding), that is a different matter and then, yes it is considered to be part of polymorphism.
inclusion polymorphism is a concept in type theory wherein a name may denote instances of many different classes as long as they are related by some common super class.
There are 2 types of polymorphism.
static
dynamic.
Overloading is of type static polymorphism.. overriding comes under dynamic (or run-time) polymorphism..
ref. http://en.wikipedia.org/wiki/Polymorphism_(computer_science) which describes it more.
No, overloading is not. Maybe you refer to method overriding which is indeed part of polymorphism.
To further clarify, From the wikipedia:
Polymorphism is not the same as method
overloading or method overriding.1
Polymorphism is only concerned with
the application of specific
implementations to an interface or a
more generic base class.
So I'd say method overriding AND method overloading and convenient features of some language regarding polymorphism but notthe main concern of polymorphism (in object oriented programming) which only regards to the capability of an object to act as if it was another object in its hierarchy chain.
Method overriding or overloading is not polymorphism.
The right way to put it is that Polymorphism can be implemented using method overriding or overloading and using other ways as well.
In order to implement Polymorphism using method overriding, you can override the behaviour of a method in a sub-class.
In order to implement Polymorphism using method overloading, you need to write many methods with the same name and the same number of parameters but with different data types and implement different behavious in these methods. Now that is also polymorphism.
Other ways to implement polymorphism is operator overloading and implementing interfaces.
Wikipedia pedantics aside, one way to think about polymorphism is: the ability for a single line of code / single method call to do different things at runtime depending on the type of the object instance used to make the call.
Method overloading does not change behaviors at runtime. Overloading gives you more choices for argument lists on the same method name when you're writing and compiling the code, but when it's compiled the choice is fixed in code forever.
Not to be confused with method overriding, which is part of polymorphism.
It's a necessary evil that is and should only be used as a complement. In the end overloads should only convert and eventually forward to the main method. OverloDing is necessary because most vms for staticalky dispatched environments don't know how to convert one type to another so the parameter fits the target and this is where one uses overloads to help out.
StringBuilder
Append(String) // main
Append(Boolean) // converts and calls append(String)
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 1 year ago.
Improve this question
I'm trying to figure out what the correct form of exceptions to throw would be for a library I am writing. One example of what I need to handle is logging a user in to a station. They do this by scanning a badge. Possible things that could go wrong include:
Their badge is deactivated
They don't have permission to work at this station
The badge scanned does not exist in the system
They are already logged in to another station elsewhere
The database is down
Internal DB error (happens sometimes if the badge didn't get set up correctly)
An application using this library will have to handle these exceptions one way or another. It's possible they may decide to just say "Error" or they may want to give the user more useful information. What's the best practice in this situation? Create a custom exception for each possibility? Use existing exceptions? Use Exception and pass in the reason (throw new Exception("Badge is deactivated.");)? I'm thinking it's some sort of mix of the first two, using existing exceptions where applicable, and creating new ones where needed (and grouping exceptions where it makes sense).
I essentially agree with your current thinking.
Use existing core exceptions where appropriate: ArgumentException, InvalidOperationException, etc. Don't try to repurpose exceptions that are specific to some other module. Use those exceptions that have a clear, generic purpose, and don't use them for business rules. For example, InvalidOperationException should indicate a bad operation w/ regards to your API, not a violation of a business rule.
For exceptions specific to your library, create a base exception class, BadgeAuthException, and always throw that. The specific scenarios should each get their own subclass (BadgeDeactivatedException, NoPermissionsAtWorkstationException, etc.) This way apps can handle the individual sub-cases separately if they want to, but they can also just catch the generic BadgeAuthException if they don't want to grovel in specifics.
Whatever you do, ensure that the Message field always contains useful information beyond just the exception name.
Use Exception and pass in the reason (throw new Exception("Badge is deactivated.");)
This certainly is a bad practice, because it violates the purpose of exceptions - not just to signal an abnormal situation, but provide an ability to distinguish exceptions on a type level, so the user of a module can make a decision depending on a type of exception.
Generally, it is good to reuse standard exceptions as far as they can fully describe abnormal situations your code actually faces. It is quite hard to give an advise in a current situation, because exceptions can often depend on semantics ( argument exception or invalid operation exception (maybe suitable for 'Their badge is deactivated' case, for example ).
You have two species of exceptions.
Those that are specific to your application, where it's good to avoid any existing exceptions.
Your application-specific exceptions should simplify the use cases for the folks who use your libraries. 3 of your application specific exceptions are things users can do. The fourth (badge does not exist) is clearly not procedural, but far more serious.
It looks like you have two application-specific errors: user-oriented things and administrative mistakes.
The others are part of some other piece of technology; i.e., database errors. You can -- generally -- ignore these. If the DB isn't available, the API will throw errors and you can let those bubble up through your library.
You can also "wrap" these as an application-specific exception which contains a lower-level exception. This is sometimes helpful if there is a lot of lower-level technology. In your case, it's just a database. Ignore it and let the DB errors bubble through.
You can nearly never go wrong by having fine-grained exception classes that extend a common base class. That way, callers who need to specifically catch some and let others through can, and callers who want to treat them all together can do so.
I think you need to have one base exception and one subtype exception for each of the situalitions you describe (actually you can make db down and internal db error to have the same base exception). The key point is that it is good practice to have your own exceptions for your library.
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 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I'd like to know how people decide whether to define a method as static. I'm aware that a method can only be defined as static if it doesn't require access to instance fields. So let's say we have a method that does not access instance fields, do you always define such a method as static, or only if you need to call it statically (without a reference to an instance).
Perhaps another way of asking the same question is whether you use static or non-static as the default?
I use static methods whenever I can. Advantages:
When calling a static method from inside an instance method, you can be sure that there are no side-effects on the state of the current object.
From inside a static method, you can be sure you don't accidentally modify any state of the object instance.
You can use a static method from outside the class without constructing an instance. If it was possible to make the method static, it clearly doesn't need an instance, so there's no need to require one.
Static methods may be slightly more efficient because no "this" pointer needs to be passed, and no dynamic dispatch is necessary.
Kevin Bourrillion wrote an insightful answer on this topic some time ago (admittedly from a Java perspective, but I think it's applicable to other languages too).
He argues that you should basically only use static methods for pure functions.
A "pure function" is any method which does not modify any state and whose
result depends on nothing but the
parameters provided to it. So, for
example, any function that performs
I/O (directly or indirectly) is not a
pure function, but Math.sqrt(), of
course, is.
I tend to agree. (Although in my own code, traditionally, I've probably used way too many static helper methods all over the place... :-P And this surely has made code that uses those methods harder to test.)
If what the method does depend solely on its arguments, you can make it static. If the method does not instantiate any other of your user defined classes, you can make it static. The default, though, is to have it as non-static.
Use static methods when you are performing operations that do not operate on instances of the class.
A perfect example would be a sqrt method of a Math class.
It depends. In languages where non-member functions are possible I'd say that most of the time, if the method could be made static, it should be made a non-member function instead, non-friend if possible. You can tell I have a mostly C++ background.
In "pure" OO languages where non-member functions are not possible it would depend on whether the method is only "incidentally" static (i.e. it just happens not to need access to instance members), or is truly logically static - it is a method of the whole class instead of for a particular instance.
Non static by default, static when I need the functionality to be available from at least two different classes, and I don't want to waste a constructor.
ps. Archimedes rules!
(C#) By default, I use static methods in static classes and non-static methods in non-static classes.
As I elaborate a class, I find myself naturally converging on making it entirely static or entirely non-static. Practially speaking, if I start wanting to define static members within a non-static class, I often find that it will eventually make the most sense to break those out into a separate static class -- either a utility class like Math or a global application class (like .NET's ConfigurationManager).
From an object-oriented perspective, a method is doing something to/with an object. So if you're using an instantiated object, it makes the most sense to me to think of that object's methods as non-static. Technically, you technically can make a non-static class have static members if they don't require access to an instance. But ostensibly, at least, a class's methods would still be doing something to/with that class, so I would still make them non-static. All things being equal, that is.
in context of python -
staticmethod are basically a normal function, we keep in the class only because of some logical reasons. classmethod takes 'class' as a first argument, default method takes instance aka self as a first argument but staticmethod does not takes any any argument.