What is better: public static Class with static methods or public Class with static methods? - class

Regarding class public class declaration, please look at these two pieces of code:
public class Helper
{
public static void CallMeganFox(string phoneNumber)
{ //...
and
public static class Helper
{
public static void CallMeganFox(string phoneNumber)
{ //...
What is better to use and why?

It's "better" in theory to make it explicit that this class is not supposed to be instantiated by making it static (second option), because it communicates intent¹.
However in such a simple case, from a practical perspective there will be exactly zero difference². Noone's going to look at this class and try to instantiate it.
¹ As Cody Gray points out, it can also help you catch mistakes earlier (e.g. forgetting to make a helper method static). While that viewpoint certainly has merit, again the practical difference is going to be negligible: the compiler would complain as soon as you tried to call the method statically in any case.
² Actually, this is not always true. For example, the C# compiler will not let you define extension methods in a non-static class -- not because it cannot, but because it wants to nudge you towards a "best practice".

static class cannot have non-static methods. If that's what you want - then use it.
More information can be found in this SO question and answers.

Related

How can a Swift module/class work around the lack of language support for "protected" members?

I'm faced with a situation where I am defining a reusable base class in a module, and I want to provide certain functions that should be callable only by subclasses, not external users of that subclass.
I'm writing a framework and packaging it as a Swift module. Part of my framework includes a base class that can be subclassed to add functionality, but whereby the derived class also has a further external purpose as well. Imagine defining a new kind of view: it derives from UIView or NSView, then provides additional logic, and is then itself instantiated by another party.
In this case, I'm the one defining the UIView-like class that is intended to be subclassed, and along with it comes a lot of private UIView internal stuff, like measurement, arranging, who knows, internal stuff.
The point is, end users of this new view class don't want to see the internals of the architecture that supported the subclassing, those should be completely inside the black box of what the subclass represents.
And it strikes me that this is now impossible in Swift.
I really don't understand why Swift got rid of protected access control. According to Apple, the function that I want to expose only to subclasses "isn't really useful outside the subclass, so protection isn’t critical".
Am I missing something? Is this a whole class of design patterns that Swift simply cannot support?
One thought that occurs to me is I could perhaps split up the public-public and the private-public parts of my class into two parts, perhaps using protocols, whereby public-public users would only see the public protocol and "private" public users would see the "private" protocol as well. Alas this seems like a lot of engineering for something that used to be free.
FWIW — I've been continually asking for better access control in Swift (including protected) since before there was access control in Swift. Now, 3.5 years after we were told to give the Swift approach to access control a try, Swift has been my primary language for almost 3 of those years and I still think the access control paradigm is clumsy and unable to model concepts that are easy in almost all similar languages.
The largest mitigating factor for me is that Swift has steered me away from ever using inheritance and subclassing 95% of the time, which I think is a good thing. So this issue comes up less than it may have otherwise. But for situations exactly as you are describing, there isn't an equivalent way to accomplish what you are doing using only protocols and protocol extensions, so you are stuck either polluting a public API with possibly harmful internal details, or using some workaround (like the one that follows) which has the smallest possible public API exposure, and simulates what you want at the cost of boilerplate and awkwardness.
That said, the approach I take is somewhat inspired by Objective C, where there is also no real protected access control, but the convention is to declare a public API header (which client code will import and reference) and a special "+Subclassing" header which only subclasses will import in their implementation, giving them visibility into the not-for-public-consumption internals.
In Swift, this isn't directly possible either, but given a class like this:
open class SomeClass {
private var foo: String
private var bar: Data
public init(){
foo = "foo"
bar = Data()
}
private func doInternalThing() {
print(foo)
}
}
You can add a nested "Protected" wrapper via extension (has to be in the same file as your class declaration), which takes an instance of the class (or a subclass) and exposes the protected-level internals as a sort of proxy:
// Create a nested "Protected" type, which can accept an instance of SomeClass (or one of its subclasses) and expose the internal / protected members on it
public extension SomeClass {
public class Protected {
unowned private var someClass: SomeClass
public var foo: String {
get {
return someClass.foo
}
set {
someClass.foo = newValue
}
}
public init(_ someClass: SomeClass) {
self.someClass = someClass
}
public func doInternalThing() {
someClass.doInternalThing()
}
}
}
Outside of the framework, in the client application, the protected members are accessed in a subclass like this:
class SomeSubclass: SomeClass {
private lazy var protected: SomeClass.Protected = { SomeClass.Protected(self) }()
func doSomething() {
protected.foo = "newFoo" // Accesses the protected property foo and sets a new value "newFoo"
protected.doInternalThing() // Prints "newFoo" by calling the protected method doInternalThing which prints the foo property.
}
}
There are pros and cons for this approach. The cons are mainly the amount of boilerplate you need to write to map all your properties and functions from the Protected wrapper to the actual class instance as shown above. Also, there is no avoiding the fact that consumers will see SomeClass.Protected as a publicly visible type, but hopefully it's clear that it shouldn't be used and it's difficult enough to use it arbitrarily that it won't happen.
The pros are that there isn't a lot of boilerplate or pain for clients when creating subclasses, and its easy to declare a lazy "protected" var to get the desired API. It's pretty unlikely that non-subclass would stumble upon or use this API accidentally or unwittingly, and it's mostly hidden as desired. Instances of SomeSubclass will not show any extra protected API in code completion or to outside code at all.
I encourage anyone else who thinks access control — or really in this case, API visibility and organization — to be easier than it is in Swift today to let the Swift team know via the Swift forums, Twitter, or bugs.swift.org.
You can kinda, sorta work around it by separating out the for-subclasses stuff into a separate protocol, like this:
class Widget {
protocol SubclassStuff {
func foo()
func bar()
func baz()
}
func makeSubclassStuff() -> SubclassStuff {
// provide some kind of defaults, or throw a fatalError if this is
// an abstract superclass
}
private lazy var subclassStuff: SubclassStuff = {
return self.makeSubclassStuff()
}()
}
Then you can at least group the stuff that's not to be called in one place, to avoid it polluting the public interface any more than absolutely necessary and getting called by accident.
You can also reconsider whether you really need the subclass pattern here, and consider using a protocol instead. Unfortunately, since protocols can't nest types yet, this involves giving the subclass-specific protocol an Objective-C-style prefixed name:
protocol WidgetConcreteTypeStuff {
...
}
protocol Widget {
var concreteTypeStuff: WidgetConcreteTypeStuff { get }
}

Very confusing Abstract Class, need guidance

I missed a few CS classes, namely the ones going over topics such as polymorphism, inheritence, and abstract classes. I'm not asking you to do my homework but I have no idea where to even start to get further guidance, so giving me a skeleton or something would help me greatly, I'm so confused.
So the problem is to create an employee abstract class with two subclasses, permanentEmployee and TempEmployee.I must store information such as name,department,and salary in these subclasses and then order them according to how the user wants them ordered. I know I start out like this
public abstract class Employee
{
}
public class TempEmployee extends Employee
{
\\variables such as name, salary, etc, here?
}
public class PermEmployee extends Employee
{
\\here too?
}
but I have no idea how to store variables in there much less access them later for ordering and displaying,. Please guidance.
If all you're looking for is an example of class-level data members in Java, this should help:
public class SomeClass {
private int someInt;
public int getSomeInt() {
return this.someInt;
}
public void setSomeInt(int someInt) {
this.someInt = someInt;
}
}
Regarding polymorphism, be aware that methods are polymorphic, but values are not. As you place values and methods (getters and setters) in your base class and derived classes, I encourage you to experiment with these concepts thoroughly. Try moving the entire value/getter/setter to the base class, try moving just the value but not the getter/setter, try putting the value in both and the getter/setter in both, etc. See how it behaves.
Make sure that any value/method/etc. that you put in your base class is applicable to all derived classes. If there's ever an exception to that rule, then you would need to move that member out of the base class and into only derived classes where it applies. Note that you can have a complex hierarchy of base classes to accommodate this if needed.
When it comes time to access these members for sorting/display/etc., consuming code would use the getters/setters. For example:
SomeClass myInstance = new SomeClass();
myInstance.setSomeInt(2);
System.out.println(myInstance.getSomeInt());
I am not sure which language you working with, but as it has "extends" I am sure you are not working with c# or CSharp, it can be Java. So I would recommend you to go for TutorialsPoint. This particular article has abstraction described here.
Just to make it easy for you, in Interface and abstraction we always create a structure or the base, it has all the common things defined or declared (Obviously interface has only methods and no variables can be declared inside it).
So as said, in above example, EmployeeId, EmployeeName, EmployeeAddress ...etc should be defined in the base class that is Abstract Base class Employee, But in TempEmployee you can have a criteria such as EmpTermPeriod, EmpContractRenewalDate, EmpExternalPayrollCompanyName (Have made names long and self descriptive) and PermEmployee to have fields like EmpJoiningDate, EmpConfirmationDate, EmpGraduityDate...etc.
I hope it helps.

Visibility separation in Swift

Since swift doesn't use headers to specify it's interface, but access modifiers instead, I wondered if there is a good way to split public and private methods (perhaps in files, extensions or just visually). I'm thinking of the Java-esque way of declaring a FooInterface and FooImpl, but I don't really like the idea. Is there a nicer way to achieve this?
The bottom line is I want to be able to have all public members in one location and the private stuff in another - it just helps to avoid visibility mistakes.
I generally use the technique of declaring a private extension:
private extension MyClass {
}
I do that later in the file. However, that only works for methods. Properties still need to be declared in the main type definition.
You can just declare the methods as private:
private func doSomething() {
}

Can one declare a static method within an abstract class, in Dart?

In an abstract class, I wish to define static methods, but I'm having problems.
In this simple example
abstract class Main {
static String get name;
bool use( Element el );
}
class Sub extends Main {
static String get name => 'testme';
bool use( Element el ) => (el is Element);
}
I receive the error:
function body expected for method 'get:name' static String get name;
Is there a typo in the declaration, or are static methods incompatible with abstract classes?
Dart doesn't inherit static methods to derived classes. So it makes no sense to create abstract static methods (without implementation).
If you want a static method in class Main you have to fully define it there and always call it like Main.name
== EDIT ==
I'm sure I read or heard some arguments from Gilad Bracha about it but can't find it now.
This behaviour is IMHO common mostly in statically typed languages (I don't know many dynamic languages). A static method is like a top level function where the class name just acts as a namespace. A static method has nothing to do with an instantiated object so inheritance is not applicable. In languages where static methods are 'inherited' this is just syntactic sugar. Dart likes to be more explicit here and to avoid confusion between instance methods and static methods (which actually are not methods but just functions because they don't act on an instance). This is not my primary domain, but hopefully may make some sense anyways ;-)
Looks like you are trying to 'override' a static method. I'm not sure what you are trying to achieve there. I'm not aware of any OO languages that support that (and not sure how they could).
A similar question in Java might help clarify Polymorphism and Static Methods
Note also that it is considered bad practice to refer to statics from an instance of the class in Java (and other OO languages). Interestingly I noticed Dart does not let you do this so is in effect removing this bad practice entirely.
So you couldn't even fool yourself into thinking it would behave polymorphically in Dart because you can't call the static from the instance.

How to Implement an Interface that Requires Duplicate Member Names?

I often have to implement some interfaces such as IEnumerable<T> in my code.
Each time, when implementing automatically, I encounter the following:
public IEnumerator<T> GetEnumerator() {
// Code here...
}
public IEnumerator GetEnumerator1() {
// Code here...
}
Though I have to implement both GetEnumerator() methods, they impossibly can have the same name, even if we understand that they do the same, somehow. The compiler can't treat them as one being the overload of the other, because only the return type differs.
When doing so, I manage to set the GetEnumerator1() accessor to private. This way, the compiler doesn't complaint about not implementing the interface member, and I simply throw a NotImplementedException within the method's body.
However, I wonder whether it is a good practice, or if I shall proceed differently, as perhaps a method alias or something like so.
What is the best approach while implementing an interface such as IEnumerable<T> that requires the implementation of two different methods with the same name?
EDIT #1
Does VB.NET reacts differently from C# while implementing interfaces, since in VB.NET it is explicitly implemented, thus forcing the GetEnumerator1(). Here's the code:
Public Function GetEnumerator() As System.Collections.Generic.IEnumerator(Of T) Implements System.Collections.Generic.IEnumerable(Of T).GetEnumerator
// Code here...
End Function
Public Function GetEnumerator1() As System.Collections.Generic.IEnumerator Implements System.Collections.Generic.IEnumerable.GetEnumerator
// Code here...
End Function
Both GetEnumerator() methods are explicitly implemented, and the compile will refuse them to have the same name. Why?
You can use explicit interface implementation:
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerator<T> GetEnumerator()
{
...
}
In Visual Basic, all interface implementations are explicit.
Interface mappings are defined by the Implements statement so you can name your interface implementation methods whatever you want. (Unlike C#, where the compiler infers which methods implement interfaces by matching their names and signatures.)
Changing the method name and visibility (as appropriate) is standard practice in VB. See Implementing Interfaces in VB.NET for a good overview.
You should be able to use Explicit Interface Implementations to create the two methods that have the same signature. Depending on what you are enumerating, I would just pass these calls through to an internal IEnumerable<T> such as a List or array.
Implementing the non-generic interface explicitly allows both methods to have the same name, and allows the non-generic version to be implemented in terms of the generic one. Along the lines of:
public class TestEnumerable : IEnumerable<int>
{
public IEnumerator<int> GetEnumerator()
{
// Type-safe implementation here.
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}