w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Is there a point to having a class with all non-static methods but no non-static fields? (or all static fields and methods along with a constructor)
Making all methods non-static allows you to override them. This makes it a lot easier to use this class in testing, because instead of the actual implementation you can use a mock that behaves as you want it for the tests. Static methods are, in my book, a code smell and should be avoided unless there's a good reason (e.g. quite trivial utility methods). Also, at some point in the future you might want to change the behaviour of the methods in some situation, e.g. in the form of a strategy. In the case of your encryption class, you might want to hand your class an instance of the encryption class to handle encrypting/decrypting, but be able to configure the details in some other place. That would allow you to change the algorithm and much more easily test your own code without also havin

Categories : Java

Calling ASP.NET page non-static methods from static web methods
You can't do it. It doesn't even make sense. The instance methods of the page are about a specific instance of the page. When you're in the static web method (page method), there is no instance of the page. If you could call the instance method from the web method, that would mean that the instance method should be a static method. Can you just add static to that method and have it still work? If not, then it depends on the particular instance of the page, and you simply can't call it when there is no instance. Note that a page instance exists only during the HTTP request that it is serving. By the time your client-side code is calling the web service, that HTTP request is already over, and the page instance is gone.

Categories : C#

Cannot access none static methods from static method, Android: getResources() from the type ContextWrapper
In Java static method can not access any non-static method or variable. One of the basic rules of working with static methods is that you can’t access a nonstatic method or field from a static method because the static method doesn’t have an instance of the class to use to reference instance methods or fields. for more information Document here is good example how to access them

Categories : Java

Do Static classes with static methods keep Entity Framework from opening too many connections
The code certainly can be called in parallel and apart from that, I see no reason why it should limit load (in a way that a non-static function wouldn't). (Whether it will execute in parallel without errors depends on shared data. Maybe there even is something with a mutex, but still I fail to see in how far static-ness changes the situation.)

Categories : C#

What's the difference between static classes, and static methods?
Your first example will not compile, a static class must have all static members. The difference between just using some static methods and a static class is that you are telling the compiler that the class cannot be instantiated. The second example you can create an object of the DEF class even though there are no instance methods in it. The ABC class cannot be instantiated with the new operator (will get a compile-time error). When to Use Static Classes Suppose you have a class CompanyInfo that contains the following methods to get information about the company name and address. C# class CompanyInfo { public string GetCompanyName() { return "CompanyName"; } public string GetCompanyAddress() { return "CompanyAddress"; } //... } These methods do not need to be attached

Categories : C#

Can non-static methods modify static variables
No, any non-static method has access to static members. The only way this would be false is if the non-static context did not have access to the static member (ex. the static member is private to a class and the non-static code is not in that class). static variables exist to provide an instance free variable/method, so for example if we have a Game class and a highscore variable, the highscore would be static (accessible without an instance), and after every game (an instance of the Game class) completes we could alter the highscore from our non-static context if our score is greater than the high score.

Categories : Java

Static synchronized methods and non-synchronized static methods confusion
static synchronized method has a lock on the class object, while non static synchronized method has a lock on the instance object (this) - so both methods can be invoked concurrently, and one thread will run 1 while the other run the 2nd. However, note that there is no race condition available in your code, because race condition requires a write, and such does not exist in these methods.

Categories : Java

When is necessary to use static methods?
From the above example test1.php helloworld() function cannot be overriden or overloaded since you have added a static keyword. However in the second example, test2.php helloworld() function can be overloaded and overriden Illustration:1 (Works) <?php class Foo { function helloWorld() { print "Hello world " ; } } class Foo1 extends Foo { function helloWorld() { echo "Foo's World"; } } $Foo1 = new Foo1(); $Foo1->helloWorld(); //Foo's World Illustration:2 (Fails) Cannot make static method Foo::helloWorld() non static <?php class Foo { static function helloWorld() { print "Hello world " ; } } class Foo1 extends Foo { function helloWorld() { echo "Foo's World"; } } $Foo1 = new Foo1(); $Foo1->hell

Categories : PHP

Static synchronized methods
Instead of taking the lock on the instance/object you are taking it on the class it self. When you lock the class you are only locking that class, not all classes. From the docs A synchronized method acquires a monitor (§17.1) before it executes. For a class (static) method, the monitor associated with the Class object for the method's class is used. For an instance method, the monitor associated with this (the object for which the method was invoked) is used.

Categories : Java

Static locals in methods and ELF OS ABI
The GNU/Linux format superseded the System V object file format, and your gcc believes that the minimum OS/ABI where your executable could be run is GNU/Linux. That usually happens when your program has symbols whose type is STT_GNU_IFUNC (a GNU extensions that denotes an indirect function), and these symbols are typically coming from glibc. When you introduced the local static variable gcc added (more) code to the translation unit to handle its initialisation and destruction (along the lines of _ZZZ__static_initialization_and_destruction_iii), and this is where the relevant parts of glibc likely came into play. First of all, your best bet is to follow the advice in this question: How to avoid STT_GNU_IFUNC symbols in your binary? Second, I have to say that on my box, both the old gcc 4

Categories : C++

Repository and static methods
If I understand correctly, your current solution is to use a static class (ProfileContext) which has the method outlined in your question. This isn't too bad but generally static classes are best avoided because they really don't play nice with unit testing. The general pattern to deal with static classes is a wrapper. e.g. public interface IMembershipWrapper { MembershipUser GetUser(string name) } Your controllers would then have a dependency property: public IMembershipWrapper membershipWrapper { get; set; } For unit testing you can use a Mock. Your concrete implementation would look like this: public class MembershipWrapper : IMembershipWrapper { public MembershipUser GetUser(string name) { return Membership.GetUser(string); } } In your case, you co

Categories : C#

Other methods of providing static content
80Mb? Are you writing a novel? If you reuse certain lines multiple times then that is really the way to go. If not, break the sections down so you can reuse certain segments instead of having a bunch of repeats in your .xml file. You could have a class or enum that is used to hold all the string literals so you can enter the text via code, but that would still take up the same amount of space. Probably even more.

Categories : Android

Linking error with static methods
This inline void OutputMessageNoNewLine(const std::string &message) { std::cout << message << " "; std::flush(std::cout); } should be this inline void ConsoleIO::OutputMessageNoNewLine(const std::string &message) { std::cout << message << " "; std::flush(std::cout); } Easy mistake to make.

Categories : C++

Decimal Formatting for Static Methods
If you want to use a decimalFormat you can like this, double d = 1.234567; DecimalFormat df = new DecimalFormat("#.##"); System.out.print(df.format(d)); This would print out 1.23. If you increase the format to "#.### it would be 1.235 Or more applicable to you would be DecimalFormat df = new DecimalFormat("#.##"); //Print Statements for the Areas System.out.println("The area of a circle with a radius of " + df.format(circleRadius) + " is " + df.format(Area.Area(circleRadius))); //Circle // do same for your others

Categories : Java

Static methods with Spring MVC and tomcat
Its OK to use static methods if you know what you're doing. If in your static method you're using only local variables ( not fields in a class ) you should then be thread-safe too. Otherwise - it is up to you do handle the synchronization and locking to keep data consistent. Spring has a limitation that you cannot use static on setters of spring beans.

Categories : Spring

Should i use Static/Shared Methods for readability:
1)If your methods are not dependent on InstanceVariable you can make them static, and in your case since you are looking towards making them all static, Static Class maybe of your interest. 2)If your methods are not logically grouped better to have them in seperate classes, but if its only about your class growing and becoming less managable you can consider thinking of partial class for the same.

Categories : Dotnet

Shall we mark private methods as "static" as more as possible?
Personally, I would mark it as static but it is not an extreme performance benefit, and is more organizational. If you work better with it static, make it static. If you are better with it being an instance method anyway, by all means do so. It's marked private, so you're free to do whatever you need/prefer to do to make it work. While it is certainly acceptable to mark your private methods as static when appropriate, there is no need to try to persuade others to do this. Private methods are designed so others' private methods need not concern you here, as would be in your case. There's no need to beg FooDev to make his method static, as he's the only one calling it anyway.

Categories : Java

Type hinting and static methods
Well, the error text explains it. You are passing an array here: $kernel->handle(Settings::appConfig())->run(); Because your Settings::appConfig() method returns an array. You have to pass an instance there.

Categories : PHP

Traits for "static" methods in Scala?
Maybe things that extend B don't want to keep re-importing A? Maybe the method relies upon other "static" methods but you actually want to override the implementation? If B is final (or an object) and the methods really are static (and don't refer to implementations that you might want to change in B), then there's not much point in mixing in a trait. The only exception is if there are implicit conversions defined, where if you mix in the implicit it will have lower priority than if you declare it yourself. (Check out scala.LowPriorityImplicits which is mixed into scala.Predef for examples.)

Categories : Scala

java: static methods and inheritance. Is there a way around this?
This seems to me to be an XY problem. That is most of your issues are with the design. For one, what is the purpose of having a private static final? Since it is final, it might as well be public. It is something that I have seen regularly, but I think it is, generally, a bad practice. Making something static, essentially makes it global. In the case of things like a singleton, there is a desire to hide the globalness, of a static variable. However, there are typically helper functions that reveal useful functionality of this "hidden, global". It sounds like the parent class lacks those methods that make the parent class fully useful. Is there a way that you can change the design of the parent class, rather than utilize all these hacks to make your project work?

Categories : Java

How Class/Static Methods get invoked
static method or variables are invoked using the class itself. e.g. if you have a static member as public static Integer age in class Employee, then you invoke it using Employee.age same goes with methods also. e.g. Employee.paySalary(); Let us consider an example. public class StaticDemo { public static void methodToPrintSomething(){ System.out.println("printing any crap"); } public static void main(String[] args) { StaticDemo.methodToPrintSomething(); StaticDemo obj = new StaticDemo(); obj .methodToPrintSomething(); } } Here method is called using obj.methodToPrintSomething(). Another interesting thing you can find is the statement obj.methodToPrintSomething(). We are creating an object to call a static method, but that does n

Categories : Java

Static Constructor and Extension methods
Wondering if my static constructor fails and throws exception if the extension methods would still work? No. If a type initializer of any kind (whether using a static constructor or not) fails, the type is basically unusable thereafter. It's very easy to demonstrate this... using System; static class Extensions { static Extensions() { Console.WriteLine("Throwing exception"); throw new Exception("Bang"); } public static void Woot(this int x) { Console.WriteLine("Woot!"); } } class Test { static void Main() { for (int i = 0; i < 5; i++) { try { i.Woot(); } catch (Exception e) { Console.WriteLine("Caught exception: {

Categories : C#

Testing static classes and methods in C# .NET
You are on the right way, and think you are not testing single line of code, in this case you are writing important test to ensure that your code interacts with membership provider in the right way, this is not simple unit test rather "mock-based" integration test. I think it worth creating all these mocks and have covered by tests this part of application. And yes, it seems overkill but no other way - either you use some helpers/libraries either wrap third-party static dependencies yourself.

Categories : C#

play framework 2 - static methods
It's not a dumb question. You could theoretically use all static methods but it is not a good coding practice. Instead you can use something like domain objects that you pass around your program. You can change the data in a domain object as it is passed around and it only exists for the life cycle of your current execution stack (that is of course unless you persist it). This will keep your program stateless and prevent you having to use all static methods.

Categories : Java

Good reasons for static methods?
By defining a method static, so a procedure that computes something, you manifest an intent to a consumer of your API about statelessness of your function. When we use static function, we do not expect it saves a state of computation or some computed internal value somewhere in it's internal static private variables, so the next call to that function may have different result even with the same parameters passed during the first call. In short: whenever you see a function that just executes an action over parameter and not preserve some state, it is a good candidate for making it static.

Categories : C#

What is the use in class/static methods in ruby?
Just as you said, they are: "accessed from the class rather than from an object and" "can have only one running at the same time." remember, too, that the class is portable

Categories : Ruby

Calling static methods/fields
The static keyword means that all instances of the class still refer to one instance of the field. That field is effectively per-class. You call it as follows: Employee.setTopSalary(12000); and access fields by: System.out.println(Employee.topSalary); Employee is the class name.

Categories : Java

NUnit - Static Vs. Public methods
Instead of keeping static methods and adding non-static methods, it's better to convert all your methods from static to instance methods and extract abstraction which clients of Foo class will depend on: public interface IFoo { void InsertUser(); void SortUser(); } public class Foo : IFoo { void InsertUser() { ... } void SortUser() { ... } } Static members introduce coupling into your application. And it's a real headache to mock static members. You should program to abstraction, instead of programing to implementation in order to make your code testable and loosely coupled. When your code depend on interface instead of static class, you can easily mock this dependency: Mock<IFoo> fooMock = new Mock<IFoo>(); fooMock.Setup(f => f.InsertUser()).Throws&

Categories : C#

doAnswer for static methods - PowerMock
PowerMockito.doAnswer(new Answer<Void>() { /* ... */ }).when(Connector.newConnection(Mockito.any(ConnectorConfig.class))); Your when is the problem. In normal Mockito, using any doAnswer/doReturn/etc call, you have to place the call you're stubbing outside of the call to when, like so: Mockito.doAnswer(new Answer<Void>() { /* ... */ }).when(yourMock).callVoidMethod(); // ^^^^^^ PowerMockito further requires that calls to static methods happen in the next statement, like so: PowerMockito.doAnswer(new Answer<Void>() { /* ... */ }).when(Connector.class); Connector.newConnection(/*...*/); // ^^^^^^ Note that the documentation I linked is actually inconsistent--looks like the docs allude to a zero-arg when, whereas the class li

Categories : Java

Inheriting static methods in Java?
Static methods don't depends on the instance, they belong to the class and only to the class, in fact if you have a static method you'll always access to one unique instance always. myObject.foo(5) is only a shortcut, what you really are doing is SuperClass.foo(5)

Categories : Java

RPC call - static methods is not working
Because RemoteServiceServlet needs to invoke your service methods somehow and the implementation expects instance methods. But this shouldn't prevent you from assigning the method data to static fields. Just be aware of multi threading.

Categories : Java

private constructor for static methods
The error is happening because you're trying to create an anonymous inner class in a static context: private static final List<String> APPROVED_LENGTH= new ArrayList<String>() { { addAll(KM_APPROVED_LIST); addAll(LM_APPROVED_LIST); } }; I'm surprised that the compiler allows this to happen, but I suppose it doesn't do a lot of semantic checks (ie, verifying that the class can be instantiated). Regardless, here's how to fix it (and a better way to initialize static lists/maps in general): private static final List<String> APPROVED_LENGTH= new ArrayList<String>(); static { addAll(KM_APPROVED_LIST); addAll(LM_APPROVED_LIST); };

Categories : Java

Should static methods modify an object or return a new one
It's not confusing, but you're getting different results. In the second case you're altering one of the inputs and maybe you don't want that. This behavior is called Side effect and it's a real pain sometimes. This is a good reason one would use functional programming (less side effects) instead of imperative languages.

Categories : C#

Passing database context to static methods
Don't make it static. You require context for those lists to be returned. Static members are designed as context less. So basically what you want is to move these methods to a class instance and provide a context upon construction via dependency injection or some other sort of factory. What is the design decision to stick to statics? An awful workaround would be passing the context once to a static field and then use it but that's basically exactly the thing you should do with a class instance

Categories : C#

Is this utility class with 2 static methods threadsafe?
Since your nameTo() method is stateless, there is no problem with it in multi-threaded contexts. Code may be shared between threads as much as you like. It’s the data which matters.

Categories : Java

Java static methods/fields in interface (again!)
You could define Identifiable to be an abstract class. Additionally, you can define another abstract class that extends Identifiable and adheres to your restrictions, ie holds the static variable and whatever methods may be necessary.

Categories : Java

Factory static methods and private constructors
The what you want to do is make Foo a singleton and make Bar assign to bar by Foo::getInstance(); For example: class Foo { private static $instance; private function __construct(){} public static function getInstance(){ if (!isset(self::$instance)){ self::$instance = new Foo(); } return self::$instance; } public function __clone(){ throw new Exception("Cannot Clone Singletons... bad programmer"); } } class Bar { static function getFooInstance() { return Foo::getInstance(); } } There is no need to replay the singleton pattern within Bar as Foo already polices it's own instantiation.

Categories : PHP

When is memory created for static methods in Java
Line two is not code that translates into JVM bytecode instructions. It's merely a declaration to the compiler to help it resolve simple names. Immediately before line eight is the latest possible moment when the ClassLoader for B will run and the static initializers (if any) for B will run. Execution of the ClassLoader for B, however, could occur earlier. The specification merely guarantees that a Class object will be loaded once and only once and not later than before its first use and that the static initializers will run once and only once and immediately before the first moment where they are needed. At line no 3 i have imported java.util.* so object will be allocated for all the class in util package. No, again, an import declaration does not translate into JVM bytecode instru

Categories : Java

python - should I use static methods or top-level functions
In Java there's the (IMHO wrong) idea to use classes everywhere, even just group together static functions that don't share any state (and thus such classes will never be instantiated). Python here begs to differ; if you have functions that don't have some shared state1 (and thus in Java would typically be static functions) and aren't tightly related to a "real" class (=one that is actually instantiated) you just use free functions inside a module. The reasoning behind this is that a class is needed only when you actually want to instantiate it, thus having a class just as a container for several functions that don't need to share an instance-specific state is useless. Actually, you can somewhat think of a module as a static class - i.e. a container of functions (=static methods), modul

Categories : Python

instance/static methods called from left to right?
The . operator has left associativity i.e operands are grouped from left So,yes it is safe to assume that they will be grouped from left to right But what is associativity? When operators have same precedence,associativity governs the order in which the operations are performed..i.e from left(operands are grouped from left) or right(operands are grouped from right) or none

Categories : Java



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.