How to Create a Private Class Method

How to create a private class method?

private doesn't seem to work if you are defining a method on an explicit object (in your case self). You can use private_class_method to define class methods as private (or like you described).

class Person
def self.get_name
persons_name
end

def self.persons_name
"Sam"
end

private_class_method :persons_name
end

puts "Hey, " + Person.get_name
puts "Hey, " + Person.persons_name

Alternatively (in ruby 2.1+), since a method definition returns a symbol of the method name, you can also use this as follows:

class Person
def self.get_name
persons_name
end

private_class_method def self.persons_name
"Sam"
end
end

puts "Hey, " + Person.get_name
puts "Hey, " + Person.persons_name

Private class as return type from public method

I've just been doing a bit of research on this and have not been able to find a definitive answer. It seems most likely that it is just an oversight on the part of the Java language designers and since it doesn't actually do any harm it has been left. It's no different really from putting a public method into a private class. Nothing stops you doing this, even though there is no way to actually access that public method.

Certainly NetBeans gives you the warning "Exporting non-public type through public API" when you try to do this. I expect most other environments will give a similar warning.

The returned object is entirely useless to anyone who tries to use it (unless they use reflection), pretty much all they can do is store it into an Object (or any other super class that they do have access to) and then pass that Object around.

You could potentially want to do this if the passed Object is being used as a "handle" that gets passed around but never operated on. In that case though it would still make much more sense to have the class public but make all the methods within it private to prevent them being acted on outside your class (or define a public interface to return and have the private class implement that).

So the answer seems to be:

It probably shouldn't be valid, but as it doesn't do any harm it has never been blocked.

There is a good answer here on a similar subject:

Exporting non-public type through public API

How to Run private class method.in same class

There are several problems here.

The first problem is the scope of your call. In the main method, you're trying to make a call to a method that requires an object reference. Main is static, displayMainMenu isn't. So, in order to call it, you need to instantiate a reference of the encapsulating class.

The next problem is the method call. displayMainMenu() is a method, not a type. So the new keyword doesn't apply here.

The next problem is the method's return type. displayMainMenu() has a return type of void. Void can't be assigned to a variable.

Try to change it to:

import java.util.*;

public class LoginPrototype {

public static void main(String[] args) {

ArrayList<Credentials> allUsers = new ArrayList<Credentials>();
LoginPrototype lp = new LoginPrototype();
lp.displayMenu();
}

private void displayMainMenu() {
//Do stuff
}
}

That solves the major problems with the code.

How to implement private method in ES6 class with Traceur

There are no private, public or protected keywords in current ECMAScript 6 specification.

So Traceur does not support private and public. 6to5 (currently it's called "Babel") realizes this proposal for experimental purpose (see also this discussion). But it's just proposal, after all.

So for now you can just simulate private properties through WeakMap (see here). Another alternative is Symbol - but it doesn't provide actual privacy as the property can be easily accessed through Object.getOwnPropertySymbols.

IMHO the best solution at this time - just use pseudo privacy. If you frequently use apply or call with your method, then this method is very object specific. So it's worth to declare it in your class just with underscore prefix:

class Animal {

_sayHi() {
// do stuff
}
}

Access an object from another class in private method

Since private is used only in declared classes and it can not be called from other classes. If you want to use it, you should use it after modifying to protected or public.

How to call a private method that exists inside a private inner class

If you want to invoke a non-static method you need to tell on which object you want to invoke it. In your case you want inner class object, but since you don't have one yet you need to create it. Since Java can't let inner class object be created without outer class object you will need to create that outer object too.

So these are steps you need to take:

  • create outer class object (if you don't have one),
  • using outer class object create inner class object,
  • invoke method on inner class object.

You can do it like this:

(you just need to remember that default constructors have same visibility as visibility of its class, so private class will have private constructor which we will need to make accessible before we will be able to use it)

try {
//creating parent object
Object outer = new MyBigClass();

//creating inner class object
Class<?> innerClass = Class.forName("MyBigClass$MyInnerClass");
Constructor<?> constructor = innerClass.getDeclaredConstructor(MyBigClass.class);//inner object must know type of outer class
constructor.setAccessible(true);//private inner class has private default constructor
Object child = constructor.newInstance(outer);//inner object must know about its outer object

//invoking method on inner class object
Method method = innerClass.getDeclaredMethod("wantedMethod",new Class<?>[]{});
method.setAccessible(true);//in case of unaccessible method
method.invoke(child,new Object[]{});

} catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

You can find more info about creating inner class object via reflection in this question

Call private class method from private instance method

First let me try to explain why the code does not work

class MyModel < ActiveRecord::Base

def self.create_instance
model = MyModel.new
# in here, you are not inside of the instance scope, you are outside of the object
# so calling model.somemething can only access public method of the object.
model.init_some_dependencies
...
end
...

You could bypass private calling of the method with model.send :init_some_dependencies. But I think in this case there is probably better solution.

I would guess that init_some_dependencies probably contain more business / domain logic rather than persistence. That's why I would suggest to pull out this logic into a "Domain Object" (or some call it Service Object). Which is just a plain ruby object that contain domain logic.

This way you could separate persistence logic to ActiveRecord and the domain logic to that class. Hence you will not bloat the ActiveRecord Model. And you get the bonus of testing
the domain logic without the need of ActiveRecord. This will make your test faster.

You could create a file say `lib/MyModelDomain.rb'

class MyModelDomain
attr_accessor :my_model

def initialize(my_model)
@my_model = my_model
end

def init_some_dependencies
my_model.property = 'some value example'
end
end

Now you could use this object say something like this

class MyModel < ActiveRecord::Base

def self.create_instance
model = MyModel.new
domain = MyModelDomain.new(model)
domain.init_some_dependencies
domain.my_model
end

def initialize_instance
# do some other work
other_init

domain = MyModelDomain.new(self)
domain.init_some_dependencies
end
end

You might also want to move the initialize_instance if you think it's necessary

Some resource that go deep into this pattern:

  • http://railscasts.com/episodes/398-service-objects
  • https://www.destroyallsoftware.com/screencasts/catalog/extracting-domain-objects

Private (implementation) class in Python

Use a single underscore prefix:

class _Internal:
...

This is the official Python convention for 'internal' symbols; "from module import *" does not import underscore-prefixed objects.

Reference to the single underscore convention.



Related Topics



Leave a reply



Submit